
C#中泛型约束就是将泛型的变量类型约束在某些范围之内而不是允许去自主指定任何类型基本语法为class 类名泛型字符1,泛型字符2 where 泛型字符1 : 泛型约束类型1 where 泛型字符2 : 泛型约束类型2 .......{}主要包括以下几类using System; namespace lesson06 { //约束泛型的变量类型为值类型 where 泛型字符 : struct class TestT where T : struct { public T value; public void TestFunK(K v) where K : struct { Console.WriteLine(v); } } //约束泛型的变量类型为引用类型 where 泛型字符 : class class Test2T where T : class { public T value; public void TestFun2K(K v) where K : class { } } //约束泛型的变量类型为存在公有无参构造函数的非抽象类类或结构体 where 泛型字符 : new() class Test3T where T : new() { public T value; public void TestFunK(K v) where K : new() { Console.WriteLine(v); } } class Test3_1 { public Test3_1 () {} } class Test3_1_1 : Test3_1 { } //约束泛型的变量类型为某一特定的类及其派生类 where 泛型字母 : 类或其派生类类名 class Test4T where T : Test3_1 { public T value; public void TestFunK(K v) where K : Test3_1 { Console.WriteLine(v); } } //约束泛型的变量类型为某接口或其派生类 where 泛型字母 : 接口或其派生 interface IFly { } class TestIFly : IFly { } class Test5T where T : IFly { public T value; public void TestFunK(K v) where K : IFly { Console.WriteLine(v); } } //约束泛型的变量类型为另一个泛型类及其派生 //where 泛型字母(代表本身或其派生 : 另一个泛型字母代表本身 class Test6T, U where T : U { public T value; public void TestFunK,V(K v) where K : V { Console.WriteLine(v); } } //约束的组合使用 class Test7T where T : class, new() { } //多泛型约束 class Test8T, K where T : class, new() where K : struct { } class Program { static void Main(string[] args) { //约束为值类型 Testint t1 new Testint(); t1.TestFunfloat(1.3f); //约束为存在无参构造类或结构体类型 Test3Test3_1 t3 new Test3Test3_1(); //约束为具体类及其派生 Test4Test3_1 t4_1 new Test4Test3_1(); Test4Test3_1_1 t4_2 new Test4Test3_1_1(); //约束为具体接口及其派生 Test5IFly t5_1 new Test5IFly(); Test5TestIFly t5_2 new Test5TestIFly(); //约束双泛型为本身与派生前是后的本身或派生 Test6TestIFly,IFly t6 new Test6TestIFly,IFly(); } } }约束允许组合使用在有多个泛型需要添加约束时直接用where连接即可。