c#隐藏混乱

Nov*_*Net 5 c#

这让我很困惑,请告诉我这个行为吗?

新成员的声明仅在新成员的范围内隐藏继承的成员.复制

**class Base
{
   public static void F() {}
}
class Derived: Base
{
   new private static void F() {}   // Hides Base.F in Derived only
}
class MoreDerived: Derived
{
   static void G() { F(); }         // Invokes Base.F
}**
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,Derived中的F声明隐藏了从Base继承的F,但由于Derived中的新F具有私有访问权限,因此其范围不会扩展到MoreDerived.因此,MoreDerived.G中的调用F()是有效的并将调用Base.F.

我不明白,static void G() { F(); }当它可以访问它的直接超类的所有方法时,如何访问基类f方法,超类隐藏了基类的f方法

Gab*_*abe 10

MoreDerived无法访问其超类的所有方法; 特别是,它无法访问private方法.在C#中,private类中标记的任何内容对该类之外的任何内容都是不可见的.换句话说,添加或删除private方法不会改变该类之外的任何内容的编译方式.由于new private static void F外部世界是不可见的,MoreDerived因此不受其影响.

如果修改器protected改为,MoreDerived 则会看到它.

在您给出的示例中,new关键字仅更改名称空间中名称的含义.它不会改变可用的方法.Derived仍然可以Base.F()像这样调用的方法:

class Derived: Base 
{ 
   new private static void F()
   {
       F();      // calls Derived.F()
       Base.F(); // calls Base.F()
   }
} 

class MoreDerived: Derived 
{ 
   static void G() 
   {
       F();         // Invokes Base.F
       Derived.F(); // Invokes Base.F because Derived.F is private
       Base.F();    // Invokes Base.F
   }
}
Run Code Online (Sandbox Code Playgroud)

它类似于这个例子:

class Foo
{
    int bar; // in most methods, this variable can be accessed as just "bar"

    Foo(int bar) // this parameter will hide the instance member bar
    {
        this.bar = bar; // instance method can still be accessed, though
    }
}
Run Code Online (Sandbox Code Playgroud)