1: 创建一个范型类MyList.cs
public class MyList<T>
{
private static int objCount = 0;
public int Count
{
get
{
return objCount;
}
}
public MyList()
{
objCount++;
}
}
2:调用范型类MyList.cs
public void MyListShow()
{
//调用范型类
MyList<int> myIntList = new MyList<int>();
MyList<int> myIntList2 = new MyList<int>();
MyList<double> myDoubleList = new MyList<double>();
Response.Write(myIntList.Count.ToString());
Response.Write(myIntList2.Count.ToString());
Response.Write(myDoubleList.Count.ToString());
}
3:范型方法的使用
public static void Copy<T>(List<T> source, List<T> destination)
{
foreach (T obj in source)
{
destination.Add(obj);
}
}
public void CopyList()
{
List<int> lst1 = new List<int>();
lst1.Add(2);
lst1.Add(4);
List<int> lst2 = new List<int>();
Copy(lst1,lst2);//调用范型方法
for (int i = 0; i < lst2.Count; i++)
{
Response.Write(lst2[i].ToString());//输出数据 }
}
}
4:范型约束的比较
//范型约束 比较
public static T Max<T>(T op1, T op2) where T : IComparable //必须继承IComparable
{
if (op1.CompareTo(op2)<0)
return op1;
return op2;
}
Response.Write(Max<int>(4, 2).ToString());//调用Max方法输出数据
5:范型与反射
public void TypeShow()
{
MyList<int> obj1 = new MyList<int>();
MyList<double> obj2 = new MyList<double>();
Type type1 = obj1.GetType();
Type type2 = obj2.GetType();
Response.Write("obj1’s Type");
Response.Write(type1.FullName);
Response.Write(type1.GetGenericTypeDefinition().FullName);
Response.Write("obj2’s Type");
Response.Write(type2.FullName);
Response.Write(type2.GetGenericTypeDefinition().FullName);
}
6:范型的继承关系
例上面的MyList.cs范型类 再建一个普通类MyList1.cs
//public class MyList1<T> : MyList<int>//此时有效 // 一个封闭结构的泛型进行派生
//public class MyList1<T> : MyList<T>//此时有效 一个开放结构的泛型进行派生
//public class MyList1 : MyList<T>此时是无效的 不能继承 会报错 //称作开放结构的泛型
public class MyList1 : MyList<int>//此时是有效的 //称作封闭结构的泛型
{
public MyList1()
{
}
}