C function coverage summary learning of recommendation
- 2021-09-24 23:32:06
- OfStack
Override class members: Modify a virtual function by the new keyword to override the virtual function.
After a virtual function is overwritten, no parent class variable can access the concrete implementation of the virtual function.
public virtual void IntroduceMyself () {...}//Parent class virtual function
public new void IntroduceMyself () {...}//Subclass overrides parent 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 class constructor
/// </summary>
public Person() {
this._name = "DefaultName";
this._age = 23;
this._gender = Genders.Male;
}
/// <summary>
/// Define virtual function IntroduceMyself()
/// </summary>
public virtual void IntroduceMyself() {
System.Console.WriteLine("Person.IntroduceMyself()");
}
/// <summary>
/// Define virtual function PrintName()
/// </summary>
public virtual void PrintName() {
System.Console.WriteLine("Person.PrintName()");
}
}
public class ChinesePerson :Person{
/// <summary>
/// Subclass constructor, indicating that from the parent class parameterless constructor call
/// </summary>
public ChinesePerson() :base(){
this._name = "DefaultChineseName";
}
/// <summary>
/// Override parent class method IntroduceMyself , using new Keyword modifies virtual function
/// </summary>
public new void IntroduceMyself() {
System.Console.WriteLine("ChinesePerson.IntroduceMyself()");
}
/// <summary>
/// Overload parent class method PrintName , using override Keyword modifies virtual function
/// </summary>
public override void PrintName(){
System.Console.WriteLine("ChinesePerson.PrintName()");
}
}
class Program
{
static void Main(string[] args)
{
// Defines two objects, 1 Parent class objects, 1 Subclass object
Person aPerson = new ChinesePerson();
ChinesePerson cnPerson = new ChinesePerson();
// Calling the overridden method, the parent class object can not call the overridden method of the subclass, but can only call its own virtual function method
aPerson.IntroduceMyself();
cnPerson.IntroduceMyself();
// Calling overloaded methods, both parent class objects and subclass objects can call methods overloaded by subclasses
aPerson.PrintName();
cnPerson.PrintName();
System.Console.ReadLine();
}
}
}
Results:
Person.IntroduceMyself()
ChinesePerson.IntroduceMyself()
ChinesePerson.PrintName()
ChinesePerson.PrintName()