泛型+多态
问:泛型 T我们常说是类的占位符,可是这个"T"是通过什么机制。来正常执行得到正确的结果呢?
答:泛型是在多态上开花结果的。
举一个简单的样例:男女平均身高是不同的,所以推断男。女身高的标准就不同,可是两者的比較过程是全然一样的。
假设我们仅仅写一个比較身高的方法。假设依照男士的平均身高进行推断。那么对女士来说就是不准确的,假设依照女士的平均身高来推断。那么对男士来说是不准确的,那么怎样做到推断男士身高依据男士平均身高。推断女士依据女士平均身高呢?对象为男士的话,调用男士对象的身高方法,对象为女士的话,调用女士的身高方法。
如今创建一个父类:
namespaceGeneric.demo { public class Person { public double height; public string name; public Person() { this.height = 1.6; this.name = "小菜"; } 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(); } } } }
如今创建一个子类
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(); } } } }
如今创建一个子类:
namespaceGeneric.demo { public class Man : Person { public Man() { this.height = 1.78; this.name = "张亮"; } 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(); } } } }
如今创建一个泛型类:
namespaceGeneric.demo { public class HeightCompare<T> where T: Person { public void IsTall(T person) { person.IsTall(); } } }
如今对泛型类进行调用
static void Main(string[] args) { //人对象 Person person=newPerson("张",1.79); HeightCompare<Person> hc =new HeightCompare<Person>(); hc.IsTall(person); //男人对象 Man man = newMan("李",1.80); HeightCompare<Man> hcm = newHeightCompare<Man>(); hcm.IsTall(man); //女人对象 Woman woman = newWoman("杨", 1.69); HeightCompare<Woman> hcw =new HeightCompare<Woman>(); hcw.IsTall(woman); }
执行结果: