Difference between shadowing and overriding in C#?

后端 未结 6 894
面向向阳花
面向向阳花 2020-11-22 07:25

What\'s difference between shadowing and overriding a method in C#?

6条回答
  •  误落风尘
    2020-11-22 07:49

    Well inheritance...

    suppose you have this classes:

    class A {
       public int Foo(){ return 5;}
       public virtual int Bar(){return 5;}
    }
    class B : A{
       public new int Foo() { return 1;}     //shadow
       public override int Bar() {return 1;} //override
    }
    

    then when you call this:

    A clA = new A();
    B clB = new B();
    
    Console.WriteLine(clA.Foo()); // output 5
    Console.WriteLine(clA.Bar()); // output 5
    Console.WriteLine(clB.Foo()); // output 1
    Console.WriteLine(clB.Bar()); // output 1
    
    //now let's cast B to an A class
    Console.WriteLine(((A)clB).Foo()); // output 5 <<<-- shadow
    Console.WriteLine(((A)clB).Bar()); // output 1
    

    Suppose you have a base class and you use the base class in all your code instead of the inherited classes, and you use shadow, it will return the values the base class returns instead of following the inheritance tree of the real type of the object.

    Run code here

    Hope I'm making sense :)

提交回复
热议问题