【问题标题】:Getting error while try to access protected accessor of property of base class in derived class尝试访问派生类中基类属性的受保护访问器时出错
【发布时间】:2013-01-08 04:05:47
【问题描述】:
 namespace PalleTech
 {          
     public class Parent
        {
            private int test = 123;
            public virtual int TestProperty
            {
                // Notice the accessor accessibility level.
                 set {
                    test = value;
                }

                // No access modifier is used here.
               protected get { return test; }
            }
        }
        public class Kid : Parent
        {
            private int test1 = 123;
            public override int TestProperty
            {
                // Use the same accessibility level as in the overridden accessor.
                 set { test1 = value / 123; }

                // Cannot use access modifier here.
               protected get { return 0; }
            }
        }
        public class Demo:Kid
        {
            public static void Main()
            {
                Kid k = new Kid();
                Console.Write(k.TestProperty);

            }
        }
    }

错误 1 ​​无法通过“PalleTech.Kid”类型的限定符访问受保护的成员“PalleTech.Parent.TestProperty”;限定符必须是“PalleTech.Demo”类型(或派生自它)

【问题讨论】:

标签: c# properties


【解决方案1】:

From MSDN Article “只有通过派生类类型进行访问时,才能在派生类中访问基类的受保护成员。”

在这里,您正在访问 Kid 的受保护设置器及其实例。您必须创建 Demo 类的实例并通过它访问。

【讨论】:

    【解决方案2】:

    Kid 类中的 TestProperty 的获取器是受保护的,这意味着如果您编写一个派生自 Kid 类的类,您可以访问 TestProperty;如果您创建Kid 类的实例,您将无法访问它。

    您可以通过从两个类的设置器中删除 protected 来更改行为;

    public class Parent
    {
        private int test = 123;
        public virtual int TestProperty
        {
            // Notice the accessor accessibility level.
            set
            {
                test = value;
            }
    
            // No access modifier is used here.
            get { return test; }
        }
    }
    public class Kid : Parent
    {
        private int test1 = 123;
        public override int TestProperty
        {
            // Use the same accessibility level as in the overridden accessor.
            set { test1 = value / 123; }
    
            // Cannot use access modifier here.
            get { return 0; }
        }
    }
    

    【讨论】:

      【解决方案3】:

      您也必须将评估器设置为受保护。 getter/setter 的访问修饰符不能比属性本身的限制更少。

      【讨论】:

        猜你喜欢
        • 2020-05-27
        • 2016-03-11
        • 2014-08-27
        • 2019-01-20
        • 1970-01-01
        • 2012-08-29
        • 2018-11-27
        相关资源
        最近更新 更多