method hiding in c# with a valid example. why is it implemented in the framework? what is the Real world advantage?

前端 未结 6 1064
春和景丽
春和景丽 2020-12-05 19:53

Can anyone explain the actual use of method hiding in C# with a valid example ?

If the method is defined using the new keyword in the d

6条回答
  •  忘掉有多难
    2020-12-05 20:43

    C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:

        using System;
        namespace Polymorphism
        {
            class A
            {
                public void Foo() { Console.WriteLine("A::Foo()"); }
            }
    
            class B : A
            {
                public new void Foo() { Console.WriteLine("B::Foo()"); }
            }
    
            class Test
            {
                static void Main(string[] args)
                {
                    A a;
                    B b;
    
                    a = new A();
                    b = new B();
                    a.Foo();  // output --> "A::Foo()"
                    b.Foo();  // output --> "B::Foo()"
    
                    a = new B();
                    a.Foo();  // output --> "A::Foo()"
                }
            }
        }
    

提交回复
热议问题