【问题标题】:C# const protected vs internalC# const 保护与内部
【发布时间】:2022-11-23 03:00:07
【问题描述】:

为什么“internal const”可以在子类中被覆盖而“protected const”不能?

示例代码:

    class A
    {
        internal const string iStr = "baseI";
        protected const string pStr = "baseP";

        void foo()
        {
            string s = B.iStr; //childI
            string t = B.pStr; //baseP
        }
    }

    class B : A
    {
        internal new const string iStr = "childI";
        protected new const string pStr = "childP";
    }

期望 B.pStr 返回“childP”。

【问题讨论】:

    标签: c# .net constants protected internals


    【解决方案1】:

    Protected members 只能在声明它们的同一个类中访问,或者在声明它们的类的派生类中访问。

    因此,B中声明的受保护的pStr,其值为“childP”,在父类A中是无法访问的。

    请注意,您没有“覆盖”任何内容,这通常涉及 override 关键字。您只是在B 中声明了两个新成员,此外那些 B 继承自 A 的。 B 总共有以下常量:

    internal const string iStr = "baseI";
    protected const string pStr = "baseP";
    internal new const string iStr = "childI";
    protected new const string pStr = "childP";
    

    B 中声明的可访问成员优先于具有相同名称的继承成员。也就是说,在B声明的成员隐藏A 中声明的那些(并且明确地使用new 声明)。因此,当您执行B.iStr 时,您会得到“childI”。但是,当您执行 B.pStr 时,您只能访问继承的成员。

    【讨论】:

      【解决方案2】:

      由于新的 const B.pStr 受到保护,因此它仅在 B 和从 B 派生的类中可见。所以,它在类A 中是不可见的。

      请注意,此上下文中的 new 关键字隐藏继承的成员。常量是静态的,不能被覆盖。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-08
        • 2011-01-23
        • 2011-03-11
        • 2012-03-27
        • 2011-01-02
        • 1970-01-01
        • 2011-03-30
        • 1970-01-01
        相关资源
        最近更新 更多