sku*_*any 2 .net c# constants protected internals
为什么“内部常量”在子类中被覆盖,而“受保护常量”却不能?
示例代码:
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";
}
Run Code Online (Sandbox Code Playgroud)
预期 B.pStr 返回“childP”。
受保护的成员只能在声明它们的同一个类中或在声明它们的类的派生类中访问。
pStr因此,在 中声明的B、值为“childP”的protected不能在父类中访问A。
请注意,您并没有“覆盖”任何内容,这通常涉及override关键字。除了继承自 的成员之外B,您只需在 中声明两个新成员。总共有以下常数:BAB
internal const string iStr = "baseI";
protected const string pStr = "baseP";
internal new const string iStr = "childI";
protected new const string pStr = "childP";
Run Code Online (Sandbox Code Playgroud)
声明的可访问成员B优先于具有相同名称的继承成员。换句话说, 中 声明的成员隐藏了B 中声明的成员A(并且使用 显式执行此操作new)。因此,当你这样做时B.iStr,你会得到“childI”。但是,当您这样做时B.pStr,您只能访问继承的成员。