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
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.