Generic + polymorphism, Polymorphism
Q: Generic T is usually a placeholder for a class. But what mechanism does this "T" use to get the correct results?
A: generics blossom on polymorphism.
To give a simple example, the average height of men and women is different, so the criteria for determining men and women are different, but the comparison process is the same. If we only write a relatively tall method, if we judge by the average height of men, it is not accurate for women. If we judge by the average height of women, so it is not accurate for men. How can we determine the average height of men based on the average height of men and the average height of women based on women? If the object is a man, the height method of the man object is called. if the object is a lady, the height method of the man object is called.
Create a parent class:
NamespaceGeneric. demo {public class Person {public double height; public string name; public Person () {this. height = 1.6; this. name = "coriander";} public Person (string name, doubleheight) {this. height = height; this. name = name;} virtual public void IsTall () {if (height> 1.68) {Console. write ("The Personnamed {0} is tall", name); Console. writeLine ();} else {Console. write ("The Personnamed {0} is short", name); Console. writeLine ();}}}}
Create a subclass
NamespaceGeneric. demo {public class Woman: Person {public Woman () {this. height = 1.68; this. name = "";} public Woman (string name, doubleheight) {this. height = height; this. name = name;} public override void IsTall () {if (height> 1.68) {Console. write ("The Womannamed {0} is tall", name); Console. writeLine ();} else {Console. write ("The Womannamed {0} is short", name); Console. writeLine ();}}}}
Create a subclass:
NamespaceGeneric. demo {public class Man: Person {public Man () {this. height = 1.78; this. name = "Zhang Liang";} public Man (string name, double height) {this. height = height; this. name = name;} public override void IsTall () {if (height> 1.78) {Console. write ("The Mannamed {0} is tall", name); Console. writeLine ();} else {Console. write ("The Womannamed {0} is short", name); Console. writeLine ();}}}}
Create a generic class:
namespaceGeneric.demo{ public class HeightCompare<T> where T: Person { public void IsTall(T person) { person.IsTall(); } }}
Now you can call generic classes.
Static void Main (string [] args) {// Person object person Person = newPerson ("Zhang", 1.79); HeightCompare <Person> hc = new HeightCompare <Person> (); hc. isTall (person); // Man man = newMan ("Li", 1.80); HeightCompare <Man> hcm = newHeightCompare <Man> (); hcm. isTall (man); // Woman woman Woman = newWoman ("yang", 1.69); HeightCompare <Woman> hcw = new HeightCompare <Woman> (); hcw. isTall (woman );}
Running result:
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.