从简单的例子理解泛型
话说有家影视公司选拔偶像派男主角,导演说了,男演员,身高是王道。于是有下面代码:
public Boy(string name, int height) {
this.mName = name;
this.mHeight = height;
}
}
//演员选拔类
public class Compare
{
//导演导超女出生,喜欢一对一PK
public Boy WhoIsBetter(Boy boy1, Boy boy2)
{
if (boy1.Height > boy2.Height)
{
return boy1;
}
else
{
return boy2;
}
}
}
//测试
static void Main(string[] args)
{
Boy boy1 = new Boy("潘长江", 165);
Boy boy2 = new Boy("刘德华", 175);
Console.WriteLine(new Compare().WhoIsBetter(boy1, boy2).Name);
Console.ReadLine();
}
public Girl(string name, int weight){
this.mName = name;
this.mWeight = weight;
}
}
//演员选拔类中添加一个女演员方法
public class Compare
{
//男演员身高是王道
public Boy WhoIsBetter(Boy boy1, Boy boy2)
{
if (boy1.Height > boy2.Height)
{
return boy1;
}
else
{
return boy2;
}
}
//女演员苗条是王道
public Girl WhoIsBetter(Girl girl1, Girl girl2)
{
if (girl1.Weight < girl2.Weight)
{
return girl1;
}
else
{
return girl2;
}
}
}
//测试
static void Main(string[] args)
{
Boy boy1 = new Boy("潘长江", 165);
Boy boy2 = new Boy("刘德华", 175);
Girl girl1 = new Girl("巩俐", 120);
Girl girl2 = new Girl("周迅", 80);
Console.WriteLine(new Compare().WhoIsBetter(boy1, boy2).Name);
Console.WriteLine(new Compare().WhoIsBetter(girl1, girl2).Name);
Console.ReadLine();
}
public Boy(string name, int height) {
this.mName = name;
this.mHeight = height;
}
public int CompareTo(object obj)
{
//比较身高
return this.mHeight - ((Boy)obj).Height;
}
}
/// <summary>
/// 女演员:实现IComparable接口
/// </summary>
public class Girl : IComparable
{
//姓名
private string mName;
//体重 www.VeVB.COm
private int mWeight;
public string Name
{
get { return this.mName; }
}
public int Weight
{
get { return this.mWeight; }
}
public Girl(string name, int weight){
this.mName = name;
this.mWeight = weight;
}
public int CompareTo(object obj)
{
//比较体重
return ((Girl)obj).Weight - this.mWeight;
}
}
Girl girl1 = new Girl("巩俐", 120);
Girl girl2 = new Girl("周迅", 80);
Console.WriteLine(((Boy)new Compare().WhoIsBetter(boy1, boy2)).Name);
Console.WriteLine(((Girl)new Compare().WhoIsBetter(girl1, girl2)).Name);
Console.WriteLine(new Compare().WhoIsBetter(boy1.Height, boy2.Height));
Console.WriteLine(new Compare().WhoIsBetter(girl1.Weight, girl2.Weight));
Console.ReadLine();
}
Girl girl1 = new Girl("巩俐", 120);
Girl girl2 = new Girl("周迅", 80);
Console.WriteLine(((Boy)new Compare().WhoIsBetter(boy1, girl1)).Name);
Console.ReadLine();
}
Girl girl1 = new Girl("巩俐", 120);
Girl girl2 = new Girl("周迅", 80);
Console.WriteLine((new Compare<Boy>().WhoIsBetter(boy1, boy2)).Name);
Console.WriteLine((new Compare<Girl>().WhoIsBetter(girl1, girl2)).Name);
Console.WriteLine(new Compare<int>().WhoIsBetter(boy1.Height, boy2.Height));
Console.WriteLine(new Compare<string>().WhoIsBetter(boy1.Name, girl1.Name));
Console.ReadLine();
}
约束 说明
T:结构 类型参数必须是值类型。可以指定除Nullable 以外的任何值类型。
T:类 类型参数必须是引用类型;这一点也适用于任何类、接口、委托或数组类型。
T:new() 类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时,new() 约束必须最后指定。
T:<基类名> 类型参数必须是指定的基类或派生自指定的基类。
T:<接口名称> 类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。
T:U 为T 提供的类型参数必须是为U 提供的参数或派生自为U 提供的参数。
新闻热点
疑难解答