what is “public new virtual void Method()” mean?

前端 未结 4 1436
悲&欢浪女
悲&欢浪女 2020-12-03 14:07

when use new virtual key words to decorate the method? what is the affection? Like define an interface, and add a class to inherit the interface. but use the new virtual to

4条回答
  •  自闭症患者
    2020-12-03 14:54

    This is called method hiding. You use this when you need to provide your own implementation for a method that cannot be overridden. Because PrinterOne.Print is not a virtual method, it cannot be overridden. Instead, the new keyword is used to create a identical method signature that hides the original method. The new method will be used instead. Adding the virtual keyword to this, allows your new method to be overridden by deriving classes.

    Your new method that hides the original will only be invoked if you call it through the defining container (eg. PrintTwo). Calling it by the interface calls the original method. Mind you, that the method was never removed or replaced so the original implementation still exists by accessing the interface directly.

提交回复
热议问题