C# - Keyword usage virtual+override vs. new

后端 未结 10 2210
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 06:06

What are differences between declaring a method in a base type \"virtual\" and then overriding it in a child type using the \"override\" keyword as

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 06:47

    I always find things like this more easily understood with pictures:

    Again, taking joseph daigle's code,

    public class Foo
    {
         public /*virtual*/ bool DoSomething() { return false; }
    }
    
    public class Bar : Foo
    {
         public /*override or new*/ bool DoSomething() { return true; }
    }
    

    If you then call the code like this:

    Foo a = new Bar();
    a.DoSomething();
    

    NOTE: The important thing is that our object is actually a Bar, but we are storing it in a variable of type Foo (this is similar to casting it)

    Then the result will be as follows, depending on whether you used virtual/override or new when declaring your classes.

提交回复
热议问题