Skip to main content
 首页 » 编程设计

c#之关于 protected 成员的可访问性

2024年02月13日12pengyingh

我已经阅读了整个互联网和书籍,protected 成员只能在类中和派生类中访问。我正在试验以下代码

  class Program 
{ 
    static void Main(string[] args) 
    { 
 
    } 
} 
abstract class A 
{ 
    protected int n_IntA = 0; 
    public abstract void AMethod(); 
} 
abstract class B : A 
{ 
    int nb; 
    public B() 
    { 
 
    } 
    public abstract void GetProtected();       
    public override void AMethod() 
    { 
 
    } 
} 
class C : B 
{ 
    public override void GetProtected() 
    { 
        // Here n_IntA is accessible why ?? 
    } 
} 

但是在 c 类中 n_IntA 是可以访问的。为什么? A 的派生类是 B。因此 n_IntA 的可访问性必须仅达到类 B ??

请您参考如下方法:

可访问性通过继承树的 ALL。

如果您没有显式隐藏某个成员,例如使用 new-operator,您可以访问继承树深处的这些成员。
查看 MSDN,了解继承的深度,尤其是在 WinForms 和 WPF 类中。如果您无法访问 System.Object 中定义的成员,整个框架就会崩溃......

来自 MSDN :

Use the access modifiers, public, protected, internal, or private, to specify one of the following declared accessibility levels for members.

...
protected | Access is limited to the containing class or types derived from the containing class.