Rewrite
The virtual method is called the virtual method. You can use override to declare a method with the same name in the subclass. This is called "override ". The corresponding method without virtual modification is called its real method.
Rewriting changes the function of the parent class method.
See the following DEMO code:
# Region Rewriting
Public class C1
{
Public virtual string GetName ()
{
Return "Xu mingxiang ";
}
}
Public class C2: C1
{
Public override string GetName ()
{
Return "xumingxiang ";
}
}
C1 c1 = new C1 ();
Console. WriteLine (c1.GetName (); // output "Xu mingxiang"
C2 c2 = new C2 ();
Console. WriteLine (c2.GetName (); // output "xumingxiang"
// Focus on this
C1 c3 = new C2 ();
Console. WriteLine (c3.GetName (); // output "xumingxiang"
# Endregion
Overwrite
In the subclass, The new Keyword is used to modify the method defined with the same name as the parent class, which is called overwrite.
Overwriting does not change the function of the parent class method.
See the following DEMO code:
# Region Overwrite
Public class C1
{
Public string GetName ()
{
Return "Xu mingxiang ";
}
}
Public class C2: C1
{
Public new string GetName ()
{
Return "xumingxiang ";
}
}
C1 c1 = new C1 ();
Console. WriteLine (c1.GetName (); // output "Xu mingxiang"
C2 c2 = new C2 ();
Console. WriteLine (c2.GetName (); // output "xumingxiang"
// Focus on this and compare it with the overwrite above
C1 c3 = new C2 ();
Console. WriteLine (c3.GetName (); // output "Xu mingxiang"
# Endregion
Summary
1: Neither rewriting nor overwriting will affect the features of the parent class (nonsense, certainly, unless the code is changed ).
2: When a child class is used to create a parent class, such as C1 c3 = new C2 (), rewriting will change the function of the parent class, that is, calling the function of the Child class, instead of overwriting, the parent class function is still called.
3: Virtual Methods and real methods can be overwritten (new), Abstract methods, and interfaces cannot.
4: Abstract METHODS, interfaces, and Methods marked as virtual can be overwritten. Real methods are not allowed.
5: The frequency of rewriting is relatively high, achieving polymorphism; the frequency of overwriting is relatively low, used to inherit classes that cannot be modified before.
Author: Xu mingxiang