c# - 为什么带有 protected 修饰符的函数可以在任何地方被覆盖和访问?

标签 c# oop d access-modifiers

我是刚接触 D 语言的 C# 程序员。我有点混淆了 D 编程语言中的 OOP。

假设我有以下类(class):

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 overridingprotected' inherited member `A.foo()'

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

最佳答案

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

public class A {
    protected virtual 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 的访问级别,我仍然允许公众访问它而且您对此无能为力。允许重新定义更简单。

关于c# - 为什么带有 protected 修饰符的函数可以在任何地方被覆盖和访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10458142/

相关文章:

python - 在这里和那里创建具有大量导入函数的类

module - D中单独模块中类的静态初始化和使用

d - 在 D 中使用 readf 读取元素数组

d - `typeof(expr)` 的效率如何?

c# - MVC 4 重用 View 和 View 模型最佳实践

c# - 为什么我不能在 ASP.NET 中使用 LINQ?

C# 捕获 Outlook 电子邮件正文

c# - 如果找不到元素,我能否在 C# 中使用 XmlSerializer 进行反序列化?

python .sort() 对 __lt__ 的优先级高于 __gt__?

javascript - 当我在函数中返回 'this' 时,代码表现不同