In the development process, in order to make a class more vitality, and sometimes use virtual to modify a method so that the subclass to overwrite it. But if there is an updated subclass to overwrite, and we do not want it to affect the overwrite of the previous layer, we need to use new virtual to block the overwrite.
For usage and example results, see the following code
Public classAnimal { Public Virtual voidWhoAmI () {Console.WriteLine ("I am Animal."); } } Public classDog:animal { Public Override voidWhoAmI () {Console.WriteLine ("I am Dog."); } } Public classDog1:animal { Public New voidWhoAmI () {Console.WriteLine ("I am DOG1."); } } Public classHomedog:dog {/// <summary> ///use new virtual to modify to block overwrite/// </summary> Public New Virtual voidWhoAmI () {Console.WriteLine ("I am Homedog."); } } Public classHuskydog:homedog { Public Override voidWhoAmI () {Console.WriteLine ("I am Huskydog."); }} [Testfixture] Public classruntest {[Test] Public voidNewandoverriderun () {Dog1 x=NewDog1 (); X.whoami (); //I am DOG1.((Animal) x). WhoAmI ();//I am Animal. //the new modified method invocation, depending on the type. } [Test] Public voidOverriderun () {Dog x=NewDog (); X.whoami ();//I am Dog. varX1 = x asAnimal; X1. WhoAmI ();//I am Dog. //method Invocation of the override modifier, depending on the type of instantiated object} [Test] Public voidNewvirtualrun () {varx =NewHomedog (); X.whoami ();//I am Homedog.((DOG) x). WhoAmI ();//I am Dog.((Animal) x). WhoAmI ();//I am Dog. //new virtual blocks the upward overwrite of the method. And the cover of dog is unaffected.} [Test] Public voidNewvirtualthenoverriderun () {varx =NewHuskydog (); X.whoami ();//I am Huskydog.((Homedog) x). WhoAmI ();//I am Huskydog.((DOG) x). WhoAmI ();//I am Dog.((Animal) x). WhoAmI ();//I am Dog. //new virtual blocks the upward overwrite, but the newly-written subclass does not overwrite it with the same result. } }code demo on overwrite blocking
How to prevent the overwrite of virtual methods in C #