C# - Keyword usage virtual+override vs. new

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

    virtual / override tells the compiler that the two methods are related and that in some circumstances when you would think you are calling the first (virtual) method it's actually correct to call the second (overridden) method instead. This is the foundation of polymorphism.

    (new SubClass() as BaseClass).VirtualFoo()
    

    Will call the SubClass's overriden VirtualFoo() method.

    new tells the compiler that you are adding a method to a derived class with the same name as a method in the base class, but they have no relationship to each other.

    (new SubClass() as BaseClass).NewBar()
    

    Will call the BaseClass's NewBar() method, whereas:

    (new SubClass()).NewBar()
    

    Will call the SubClass's NewBar() method.

提交回复
热议问题