rewrite
Overriding changes the functionality of the parent class method.
See the demo code below:
public class C1
{
public virtual string GetName()
{
return "叔祥";
}
}
public class C2 : C1
{
public override string GetName()
{
return "xiangshu";
}
}
C1 c1 = new C1();
Console.WriteLine(c1.GetName());//输出“祥叔”
C2 c2 = new C2();
Console.WriteLine(c2.GetName());//输出“xiangshu”
// focus on here
Console.WriteLine(c3.GetName());//输出“xiangshu”
#endregion
the method defined in the subclass with the new keyword with the same name as the superclass is called overriding.
public class C1
{
public string GetName()
{
return "祥叔";
}
}
public class C2 : C1
{
public new string GetName()
{
return "xiangshu";
}
}
C1 c1 = new C1();
Console.WriteLine(c1.GetName());//输出“祥叔”
C2 c2 = new C2();
Console.WriteLine(c2.GetName());//输出“xiangshu”
// Focus on this, compare with the rewriting above
Console.WriteLine(c3.GetName());//Output "Uncle Xiang"
#endregion
Summarize
1: Whether it is rewriting or overwriting, it will not affect the function of the parent class itself (nonsense, sure, unless the code is changed).
2: When a subclass is used to create a parent class, such as C1 c3 = new C2(), overwriting will change the function of the parent class, that is, calling the function of the subclass; while overwriting will not, the function of the parent class will still be called.
3: Both virtual and real methods can be overridden (new), but abstract methods and interfaces cannot.
4: Abstract methods, interfaces, methods marked as virtual can be overridden (override), but real methods cannot.
5: The frequency of rewriting is relatively high to achieve polymorphism; the frequency of overwriting is relatively low, when it is used to inherit classes that could not be modified before.