C# - Keyword usage virtual+override vs. new

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

    The new keyword actually creates a completely new member that only exists on that specific type.

    For instance

    public class Foo
    {
         public bool DoSomething() { return false; }
    }
    
    public class Bar : Foo
    {
         public new bool DoSomething() { return true; }
    }
    

    The method exists on both types. When you use reflection and get the members of type Bar, you will actually find 2 methods called DoSomething() that look exactly the same. By using new you effectively hide the implementation in the base class, so that when classes derive from Bar (in my example) the method call to base.DoSomething() goes to Bar and not Foo.

提交回复
热议问题