问:泛型 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);
}
运行结果: