1 class Program {
2 static void Main(string[] args) {
3
4 }
5 }
6
7 interface IMyInterface {
8 void Method1();
9 }
10
11 //一、六种类型约束
12 //1、类型参数必须是引用类型
13 class MyClass1<T> where T : class {}
14 //2、类型参数必须是值类型
15 class MyClass2<T> where T : struct {}
16 //3、类型参数必须具有无参公共构造函数
17 class MyClass3<T> where T : new() {}
18 //4、类型参数必须是指定的类型或及其子类
19 class MyClass4<T> where T : Program { }
20 //5、类型参数必须是实现了指定接口的对象
21 class MyClass5<T> where T : IMyInterface { }
22 //6、U类型参数必须为T类型或及其子类
23 class List<T>
24 {
25 void Method<U>(List<U> items) where U : T
26 {
27 //TODO
28 //Do something...
29 }
30 }
31
32 //二、约束可以用于类、方法和委托
33 delegate void MyDelegate<T>() where T:class;