object-oriented programming will definitely use inheritance. In some cases, how do you assign the value of the parent class to the subclass? A new parent class instance, a new subclass instance, and each attribute is assigned a value. In essence, the assignment is true, but it is troublesome to assign values one by one in the Program , this process can be summarized as a method.
parent class:
Public class parentclass {private string id = string. empty; private string name = string. empty; private int age = 0; private string address = string. empty; // <summary> // ID // </Summary> Public String ID {get {return ID;} set {id = value ;}} /// <summary >/// name /// </Summary> Public string name {get {return name ;}set {name = value ;}} /// <summary >/// age /// </Summary> Public int age {get {return age;} set {age = value ;}} /// <summary >/// address /// </Summary> Public String address {get {return address;} set {address = value ;}}}
Subclass:
Public class childclass: parentclass {private decimal scored = 0; private Int? Rank = NULL; // <summary> // score // </Summary> Public decimal scored {get {return scored;} set {scored = value ;}} /// <summary> /// ranking /// </Summary> Public Int? Rank {get {return rank;} set {Rank = value ;}}}
The method of assigning a value to the subclass by traversing the attributes of the parent class:
Private Static childclass autocopy (parentclass parent) {childclass child = new childclass (); var parenttype = typeof (parentclass); var properties = parenttype. getproperties (); foreach (VAR propertie in properties) {If (propertie. canread & propertie. canwrite) {propertie. setvalue (child, propertie. getvalue (parent, null), null) ;}return child ;}
Call:
Static void main (string [] ARGs) {parentclass parent = new parentclass (); parent. id = "01"; parent. name = "Sam"; parent. age = 26; parent. address = "Beijing"; childclass child = autocopy (parent); child. scored = 90; child. rank = 1; string result = string. format ("ID: {0} name = {1} age = {2} address = {3}", child. ID, child. name, child. age, child. address); string resultextend = string. format ("scored: {0} Rank = {1}", child. scored, child. rank); console. writeline (result); console. writeline (resultextend); console. readline ();}
Output result:
CodeDownload: http://download.csdn.net/detail/yysyangyangyangshan/5540909