C # function coverage summary learning,
Override class member: the virtual function is replaced by the new keyword.
After a virtual function is overwritten, no parent variable can access the specific implementation of the virtual function.
Public virtual void IntroduceMyself () {...} // parent class virtual function
Public new void IntroduceMyself () {...} // subclass overwrites the parent class virtual function
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace MethodOverrideByNew
{
Public enum Genders {
Female = 0,
Male = 1
}
Public class Person {
Protected string _ name;
Protected int _ age;
Protected Genders _ gender;
/// <Summary>
/// Parent Constructor
/// </Summary>
Public Person (){
This. _ name = "DefaultName ";
This. _ age = 23;
This. _ gender = Genders. Male;
}
/// <Summary>
/// Define the virtual function IntroduceMyself ()
/// </Summary>
Public virtual void IntroduceMyself (){
System. Console. WriteLine ("Person. IntroduceMyself ()");
}
/// <Summary>
/// Define the virtual function PrintName ()
/// </Summary>
Public virtual void PrintName (){
System. Console. WriteLine ("Person. PrintName ()");
}
}
Public class ChinesePerson: Person {
/// <Summary>
/// Subclass constructor, indicating that the constructor is called from the parent class without Parameters
/// </Summary>
Public ChinesePerson (): base (){
This. _ name = "DefaultChineseName ";
}
/// <Summary>
/// Overwrite the parent class method IntroduceMyself and use the new keyword to modify the virtual function
/// </Summary>
Public new void IntroduceMyself (){
System. Console. WriteLine ("ChinesePerson. IntroduceMyself ()");
}
/// <Summary>
/// Reload the parent class method PrintName and use the override keyword to modify the virtual function
/// </Summary>
Public override void PrintName (){
System. Console. WriteLine ("ChinesePerson. PrintName ()");
}
}
Class Program
{
Static void Main (string [] args)
{
// Define two objects, one parent object and one subclass object
Person aPerson = new ChinesePerson ();
ChinesePerson cnPerson = new ChinesePerson ();
// Call the override method. A parent class object cannot call a method that has been overwritten by a subclass. It can only call its own virtual function method.
APerson. IntroduceMyself ();
CnPerson. IntroduceMyself ();
// Call the overload method. Both the parent class object and the subclass object can call the method after the subclass is overloaded.
APerson. PrintName ();
CnPerson. PrintName ();
System. Console. ReadLine ();
}
}
}
Result:
Person. IntroduceMyself ()
ChinesePerson. IntroduceMyself ()
ChinesePerson. PrintName ()
ChinesePerson. PrintName ()