Overwrite class member: the virtual function is overwritten by the new keyword to overwrite the virtual function.
When 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 a 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 {PROTECTE
D 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>///defines virtual functions introducemyself ()///</summary> public virtual void introducemyself (
) {System.Console.WriteLine ("person.introducemyself ()"); ///<summary>///defines virtual functions printname ()///</summary> public virtual void Printname () {Sy Stem.
Console.WriteLine ("Person.printname ()");
The public class Chineseperson:P erson{///<summary>///Subclass constructor, indicating that the call from the parent class parameterless constructor is///</summary> Public Chineseperson (): Base () {This._name= "Defaultchinesename"; ///<summary>///overrides the parent class method Introducemyself, using the new keyword to modify the virtual function///</summary> public new void Introdu
Cemyself () {System.Console.WriteLine ("chineseperson.introducemyself ()"); ///<summary>///Overloaded Parent class method Printname, using the Override keyword to modify virtual functions///</summary> public override void Pri
Ntname () {System.Console.WriteLine ("chineseperson.printname ()"); The class program {static void Main (string[] args) {//Define two objects, a parent class object, a subclass object person Aperson = n
EW Chineseperson ();
Chineseperson Cnperson = new Chineseperson ();
Calls the overridden method, the parent class object cannot invoke the method overridden by the subclass, and can only invoke its own virtual function method Aperson.introducemyself ();
Cnperson.introducemyself ();
Call overloaded methods, and both parent and subclass objects can invoke the method Aperson.printname () after the child class overload;
Cnperson.printname ();
System.Console.ReadLine (); }
}
}
Results:
Person.introducemyself ()
Chineseperson.introducemyself ()
Chineseperson.printname ()
Chineseperson.printname ()
The above C # function coverage summary learning (recommended) is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.