概述
泛型类和泛型方法兼具可重用性、类型安全性和效率,这是非泛型类和非泛型方法无法实现的
泛型通常与集合以及作用于集合的方法一起使用
泛型所属命名空间:System.Collections.Generic
可以创建自定义泛型接口、泛型类、泛型方法、泛型事件和泛型委托,以提供自己的通用解决方案,设计类型安全的高效模式
泛型允许编写一个可以与任何数据类型一起工作的类或方法
示例
- 1 using System;
- 2 using System.Collections.Generic;
- 3
- 4 namespace GenericTest
- 5 {
- 6 public class TestGeneric<T>
- 7 {
- 8
- 9 private T[] array;
- 10 public TestGeneric(int i)
- 11 {
- 12 array = new T[i + 1];
- 13 }
- 14 public T GetItem(int index)
- 15 {
- 16 return array[index];
- 17 }
- 18 public void setItem(int index, T value)
- 19 {
- 20 array[index] = value;
- 21 }
- 22 }
- 23
- 24 class Tester
- 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的祖先,即继承的接口或类
代码尝试使用某个约束所不允许的类型来实例化类,则会产生编译时错误
定义:public T GetInfo<T>(string id) where T : CBaseInfo
约束限定条件
- 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>