namespace Lesson6_泛型约束 { #region 知识回顾 //泛型类 class TestClass { public T t; public U u; public U TestFun(T t) { return default(U); } //泛型函数 public V TestFun(K k) { return default(V); } } #endregion #region 知识点一 什么是泛型约束 //让泛型的类型有一定限制 //关键字:where //泛型约束一共有6种 //1.值类型 where 泛型字母:struct //2.引用类型 where 泛型字母:class //3.存在无参公共构造函数 where 泛型字母:new() //4.某个类本身或其派生类 where 泛型字母:类名 //5.某个接口的派生类 where 泛型字母:接口名 //6.另一个泛型类本身或派生类 where 泛型字母:另一个泛型字母 #endregion #region 知识点二 各泛型约束讲解 class Test1 where T : struct { public T v; public void TestFun(K v) where K : struct { } } class Test2 where T : class { public T value; public void TestFun(K v) where K : class { } } class Test3 where T: new() { public T value; public void TestFun(K v) where K : new() { } } class Test1 { } class Test2 { public Test2(int i) { } } class Test4 where T : Test1 { public T value; public void TestFun(K v) where K : Test1 { } } class Test3 : Test1 { } interface IFly { } class Test4 : IFly { } class Test5 where T : IFly { public T value; public void TestFun(K v) where K : IFly { } } class Test6 where T : U { public T value; public void TestFun(K k) where K : V { } } #endregion #region 知识点三 约束的组合使用 class Test7 where T : class, new() { } #endregion #region 知识点四 多个泛型有约束 class Test8 where T:class,new() where K : struct { } #endregion #region 总结 //泛型约束: 让类型有一定限制 //class //struct //new() //类名 //接口名 //另一个泛型字母 //注意: //1.可以组合使用 //2.多个泛型约束 用where连接即可 #endregion internal class Program { static void Main(string[] args) { TestClass t = new TestClass(); t.t = "123fgd"; t.u = 10; t.TestFun("123"); t.TestFun(123); //Test1 t1 = new Test1;//Object类型不能为空,所以报错 Test1 t1 = new Test1();//int是值类型,所以可以放 //t1.TestFun();//不可为空同样报错 t1.TestFun(1.3f); //Test2 t2 = new Test2;//因为是引用类型所以值类型int会报错 Test2 t2 = new Test2(); t2.TestFun("123"); t2.TestFun(new object()); t2.value = new Random(); Test3 t3 = new Test3();//如果Test1的构造函数是私有也会报错 //Test3 t4 = new Test3();//test2有参所以报错,如果test2是无参但抽象类也会报错,必须是有公共无参构造函数的非抽象类 //Test3 t4 = new Test3();//没问题,struct值类型是默认有无参构造且不会被顶替的 Test4 t4 = new Test4();//Test3是继承约束的Test1的类,所以也不会报错 Test5 t5 = new Test5(); t5.value = new Test4();//继承IFly的Test4 Test6 t6 = new Test6 (); Test6 tx = new Test6(); } } }