What are Virtual Methods?

前端 未结 14 615
傲寒
傲寒 2020-11-29 03:02

Why would you declare a method as \"virtual\".

What is the benefit in using virtual?

14条回答
  •  忘掉有多难
    2020-11-29 03:46

    Virtual Methods on MSDN

    The virtual keyword is used to modify a method or property declaration, in which case the method or the property is called a virtual member. The implementation of a virtual member can be changed by an overriding member in a derived class.

    When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member. (For more information on run-time type and most derived implementation, see 10.5.3 Virtual methods.)

    By default, methods are non-virtual. You cannot override a non-virtual method.

    You cannot use the virtual modifier with the following modifiers:

    static abstract override

    Virtual properties behave like abstract methods, except for the differences in declaration and invocation syntax.

    • It is an error to use the virtual modifier on a static property.
    • A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.

提交回复
热议问题