Difference between overrid and new modifier in C # (CODE ),
In C # inheritance, you can use the related modifiers override and new. Both modifiers can override the parent class method with the same name in the new subclass.
Override: Used to extend or modify the abstract or virtual Implementation of inherited methods, attributes, indexers, or events.
New: when used as a declaration modifier,newKeywords can explicitly hide members inherited from the base class. When the inherited member is hidden, the derived version of the member replaces the base class version.
The above are the explanations of these two modifiers. There are many differences between the two, most of which are conceptual. I will share with you the code for self-testing.
1 using System; 2 3 public class BaseClass {4 public virtual void ShowA () {5 Console. writeLine ("A"); 6} 7 8 public void ShowB () {9 Console. writeLine ("B"); 10} 11 12 public void ShowAB () {13 ShowA (); 14 ShowB (); 15} 16} 17 18 public class TestClass: baseClass {19 public override void ShowA () {20 Console. writeLine ("AA"); 21} 22 23 public new void ShowB () {24 Console. writeLine ("BB"); 25} 26} 27 28 public class Example29 {30 public static void Main () 31 {32 TestClass test = new TestClass (); 33 test. showA (); 34 test. showB (); 35 test. showAB (); 36 37 BaseClass test1 = new TestClass (); 38 test. showA (); 39 test. showB (); 40 test. showAB (); 41 42 Console. readLine (); 43 Console. writeLine ("Running ended"); 44} 45}
The output result is as follows:
It can be seen that override is equivalent to modifying the parent class method and overwrites the parent class method. When called in the parent class method, the overwritten class is also called. Override overrides the method implementation information under the parent class address.
For new, there is no impact on the methods in the parent class. When the parent class method is called, the method of the parent class will still be executed. When the subclass method is called, The subclass method is called. Only the method names are the same, causing the subclass to cause a hidden feature to the method of the parent class. New is equivalent to opening up a new method implementation location. The sub-class and parent class methods have different addresses.