简体   繁体   中英

c# hiding confusion

This is confusing to me please expalin me the behaviour of this?

A declaration of a new member hides an inherited member only within the scope of the new member. Copy

**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
}**

In the example above, the declaration of F in Derived hides the F that was inherited from Base, but since the new F in Derived has private access, its scope does not extend to MoreDerived. Thus, the call F() in MoreDerived.G is valid and will invoke Base.F.

I am not understanding that how static void G() { F(); } static void G() { F(); } can access the base class f method when it can access all methods of it's immediate super class and super class hides the f method of base class

MoreDerived cannot access all methods of its super class; in particular, it cannot access private methods. In C#, anything marked private in a class is invisible to anything outside of that class. In other words, adding or removing a private method will not change how anything outside of that class compiles. Since the new private static void F is invisible to the outside world, MoreDerived is unaffected by it.

If the modifier was protected instead, MoreDerived would see it.

In the example you gave, the new keyword only changes the meaning of names in the namespace. It does not change what methods are available. A method of Derived can still call Base.F() like so:

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
   }
}

It's analogous to this example:

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
    }
}

'new' keyword will hide the base member if it is allowded to be access outside the class.

But due to the inheritance chain MoreDerived : Derived : Base , you will see the public members of immeditae base or the higher base classes in the chain.

Method hiding is not equal to the private modifier on a method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM