1 usingSystem; 2 usingSystem.Collections.Generic; 3 4 namespaceGenericTest 5 { 6 public class TestGeneric<T> 7 { 8 9 privateT[] array; 10 public TestGeneric(inti) 11 { 12 array = new T[i + 1]; 13 } 14 public T GetItem(intindex) 15 { 16 returnarray[index]; 17 } 18 public void setItem(intindex, T value) 19 { 20 array[index] =value; 21 } 22 } 23 24 classTester 25 { 26 static void Main(string[] args) 27 { 28 TestGeneric<char> MyArray = new TestGeneric<char>(5); 29 for (int i = 0; i < 5; i++) 30 { 31 MyArray.setItem(i, (char)(i + 97)); 32 } 33 34 for (int i=0; i<5; i++) 35 { 36 Console.WriteLine(MyArray.GetItem(i)); 37 } 38 Console.WriteLine(); 39 Console.ReadKey(); 40 } 41 42 } 43 }
结果
约束
约束限定条件
- T:struct 类型参数必须是值类型。可以指定除 Nullable 以外的任何值类型
- T:class 类型参数必须是引用类型,包括任何类、接口、委托或数组类型
- T:new() 类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时new() 约束必须最后指定
- T:<基类名> 类型参数必须是指定的基类或派生自指定的基类
- T:<接口名称> 类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。
- T:U 为 T 提供的类型参数必须是为 U 提供的参数或派生自为 U 提供的参数,称为裸类型约束
例:
public class Myarray<T> : B<T> where T : new() { }
定义多个类型参数和约束:
public class Base<A,B,C> where A: struct where B: new() where C: class { }
泛型也可以继承泛型:
class D:C<string,int> class E<U,V>:C<U,V> class F<U,V>:C<string,int>