C# - Keyword usage virtual+override vs. new

后端 未结 10 2213
被撕碎了的回忆
被撕碎了的回忆 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:44

    My version of explanation comes from using properties to help understand the differences.

    override is simple enough, right ? The underlying type overrides the parent's.

    new is perhaps the misleading (for me it was). With properties it's easier to understand:

    public class Foo
    {
        public bool GetSomething => false;
    }
    
    public class Bar : Foo
    {
        public new bool GetSomething => true;
    }
    
    public static void Main(string[] args)
    {
        Foo foo = new Bar();
        Console.WriteLine(foo.GetSomething);
    
        Bar bar = new Bar();
        Console.WriteLine(bar.GetSomething);
    }
    

    Using a debugger you can notice that Foo foo has 2 GetSomething properties, as it actually has 2 versions of the property, Foo's and Bar's, and to know which one to use, c# "picks" the property for the current type.

    If you wanted to use the Bar's version, you would have used override or use Foo foo instead.

    Bar bar has only 1, as it wants completely new behavior for GetSomething.

提交回复
热议问题