c#-4.0 - 在子类中访问父类的 protected 字段

标签 c#-4.0

我试图在子类中以不同的方式访问 protected 成员变量。我发现我不能通过使用子类对父类对象的对象引用来做到这一点。这里我指的是下面程序中的“int Number6”。

但是我可以访问公开的“int Number7”。我想知道这背后的原因。

public class Customer
{
    #region Fields



    protected int Number2; 
    protected int Number3;
    protected int Number4;
    protected int Number5;
    protected int Number6;

    public    int Number7;

    #endregion


}

public class CorporateCustomer : Customer
{
    public void PrintID()
    {
        CorporateCustomer CC = new CorporateCustomer();
        CC.Number2 = 101;

        base.Number3 = 103;

        this.Number4 = 104;            

        Customer C2 = new CorporateCustomer();
        C2.Number6 = 106; //->  Not Possible to access protected Number6 by this way                        

        C2.Number7  = 105; //-> However, can access public field                 

    }
}

最佳答案

有趣的问题 - the msdn states that this won't work :

A protected member of a base class is accessible in a derived class only if the access occurs through the derived class type.

由于您使用的是基类型而不是派生类型,因此这不起作用。

但是为什么呢?我可以想象这与客户也可以由 CorporateCustomer 之外的另一个类派生的问题有关。在这种情况下,您分配给 Customer 的实例不一定是 CorporateCustomer,因此 protected 属性正确地禁止访问 Number6 属性,因为这会破坏可访问性限制。

    public class PrivateCustomer : Customer
    {
    }

    public class CorporateCustomer : Customer
    {
        public void PrintID()
        {

            Customer C = new PrivateCustomer();
            C.Number6 = 106; //->  Not Possible to access protected Number6 by this way which is alright, as this is not a Corporate Customer                       

            C.Number7 = 105; //-> However, can access public field                 

        }
    }

C# 语言规范准确地说明了此示例作为此不起作用的原因:

3.5.3 Protected access for instance members When a protected instance member is accessed outside the program text of the class in which it is declared, and when a protected internal instance member is accessed outside the program text of the program in which it is declared, the access must take place within a class declaration that derives from the class in which it is declared. Furthermore, the access is required to take place through an instance of that derived class type or a class type constructed from it. This restriction prevents one derived class from accessing protected members of other derived classes, even when the members are inherited from the same base class.

关于c#-4.0 - 在子类中访问父类的 protected 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28348415/

相关文章:

c#-4.0 - Spec# 是否足够稳定以使用?

c# - 如何使用 "dynamic"变量从匿名类型读取属性

caching - 用于将引用类型的保存/选择列表保存到 redis 中的 API

c# - 如何将类型 System.Collections.Specialized.StringCollection 转换为字符串 []

c# - 字典的 JSON 序列化为名称 :value instead of {name:name, 值:值}

security - 为 C# 评估器提供沙盒应用程序域的最佳证据

string - 如何在 C# 中优化这个 UserAgent 解析器 for 循环?

unit-testing - 如何对事件订阅进行单元测试

c# - 如何诊断句柄泄漏源

c# - .Net 从哪个版本开始支持 httpclient