c# – 为什么具有受保护修饰符的函数可以被覆盖并且可以在每个位置访问?

栏目: ASP.NET · 发布时间: 5年前

内容简介:翻译自:https://stackoverflow.com/questions/10458142/why-a-function-with-protected-modifier-can-be-overridden-and-accessible-every-wh

我是D语言新手的C#程序员.我对D编程语言中的OOP有点困惑.

假设我有以下课程:

public class A {
   protected void foo() {
      writefln("A.foo() called.");
   }
};

public class B : A {
   public override void foo() {
      writefln("B.foo() called.");
   }
};

protected修饰符意味着我只能在继承的类上访问.foo()方法,为什么这个D程序正常编译?

这相当于C#.NET:

using System;

public class A {
   protected virtual void foo() {
      Console.WriteLine("a.foo() called.");
   }
};

public class B : A {
   public override void foo() {
      Console.WriteLine("b.foo() called.");
   }
};

public class MainClass  {
   public static void Main(string[] args) {
      A a = new A();
      B b = new B();    
      a.foo();
      b.foo();
   }
};

它不编译并给出以下错误消息(如我所料):

test.cs(10,30): error CS0507:

B.foo()': cannot change access

  modifiers when overriding
protected’ inherited member `A.foo()’

有人可以解释这个D行为吗?提前致谢.

防止覆盖没有任何意义.派生类可以实现允许访问的简单转发功能.考虑:

public class A {
    protected void foo() {
        writefln("A.foo() called.");
    }
};

public class B : A {
   protected override void foo() { // OK
       writefln("B.foo() called.");
   }
   public void call_foo() {
       foo(); // But I allowed public access anyway!
   }
};

因此,即使我没有重新定义foo的访问级别,我仍然允许公共访问它,并且你无能为力.允许重新定义更简单.

翻译自:https://stackoverflow.com/questions/10458142/why-a-function-with-protected-modifier-can-be-overridden-and-accessible-every-wh


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Coding the Matrix

Coding the Matrix

Philip N. Klein / Newtonian Press / 2013-7-26 / $35.00

An engaging introduction to vectors and matrices and the algorithms that operate on them, intended for the student who knows how to program. Mathematical concepts and computational problems are motiva......一起来看看 《Coding the Matrix》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具