public class MyList<T>
{
T[] arr;
public MyList(T[] arrp)
{
arr = arrp;
}
}
public static void Main(string []arg)
{
MyList<string>list = new MyList<string>();
}
public class List<T,F> { }public static void Main(string []arg) { MyList<string,Person>list = new MyList<string,Person>(); }
2.泛型-类继承
继承一个泛型类时,必须为其传递泛型参数!public class Father<K,V>{} //父类定义子类时直接为父类泛型参数赋值
public class Son : Father<int,string>定义子类时把子类泛型参数赋给父类泛型参数
public class Son<W,Y> : Father<W,Y>定义子类时把子类泛型参数,同时为父类泛型参数赋值
public class Son<W,Y> : Father<int,string>错误:public class Son : Father<K,V> //K,V不存在3.泛型约束-基类约束:用来约束 泛型参数 必须是某个类 或 某个类的子类class Dog { public void Shout() { } } class Cat { public void Walk() { } } class House<TPet,TPet2> where TPet:Dog where TPet2:Cat { public C(TPet p1, TPet2 p2) { p1.Shout(); p2.Walk(); } }注:一个泛型参数不允许多个基类约束
不能为密封类指定基类约束(string)
也不能用Nullable<T>
4.泛型约束-接口约束:用来约束泛型参数 必须是某个类 或 某个类的子类
interface IGetReward<T> { T GetReward(); } interface IWalk { void Walk(); } interface ISing<T> { T Sing(); } class MyPetPlay<T, V> where T : IGetReward<T> where V : IWalk, ISing<V> { public MyClass(T t,V v) { t.GetReward(); //直接调用接口方法 v.Walk(); v.Sing(); } }
5.泛型约束-class/struct约束
public struct A{ } public class B{ } public class C<T> where T : struct //值类型 { } public class C2<T> where T : class //引用类型 { }
6.泛型约束-构造器约束
class Dog { public Dog(){ } } class Cat { public Cat(int age){ } } class Pet<T> where T : new() //C#只支持无参数的构造器约束 { T t; public Pet() { t = new T(); } } public static void Main(string[]arg) { Pet<Dog> c = new Pet<Dog>(); Pet<Cat> d = new Pet<Cat>();//异常 }
原文:http://blog.csdn.net/ankeyuan/article/details/21991105