C#泛型约束
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#泛型约束,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2436字,纯文字阅读大概需要4分钟。
内容图文
![C#泛型约束](/upload/InfoBanner/zyjiaocheng/647/d42ffa3a1a9e4cd9bc3a3a4009f7771e.jpg)
1. where T : struct 对于结构约束,类型T必须是值类型
2. where T : class 对于类约束,类型T必须是引用类型
3. where T : 接口名称IFoo 对于指定接口IFoo约束,类型T必须实现指定接口IFoo
4. where T : 类名Foo 对于指定类Foo约束,类型T必须是Foo对象或者是继承自Foo得对象
5. where T : new() 构造函数约束,类型T必须有一个无参构造函数
6. where T1:T2 裸类型约束,类型T1派生自泛型类型T2
where T : struct | 对于结构约束,类型T必须是值类型 |
where T : class | 对于类约束,类型T必须是引用类型 |
where T : 接口名称IFoo | 对于指定接口IFoo约束,类型T必须实现指定接口IFoo |
where T : 类名Foo | 对于指定类Foo约束,类型T必须是Foo对象或者是继承自Foo得对象 |
where T : new() | 构造函数约束,类型T必须有一个无参构造函数 |
where T1:T2 | 裸类型约束,类型T1派生自泛型类型T2 |
1.
static void Main(string[] args) { TestT(123); TestT('a'); //TestT("123"); 报错 Console.ReadKey(); } public static void TestT<T>(T t) where T : struct { Console.WriteLine(t.GetType()); }
2.
static void Main(string[] args) { TestT("123"); //TestT(123);//报错 Console.ReadKey(); } public static void TestT<T>(T t) where T : class { Console.WriteLine(t.GetType()); }
3.
class Program { static void Main(string[] args) { TestClass testClass = new TestClass(); TestT(testClass); Object obj = new Object(); //TestT(obj);//报错 Console.ReadKey(); } public static void TestT<T>(T t) where T : TestInterface { Console.WriteLine(t.GetType()); } } interface TestInterface { } class TestClass : TestInterface { }
4.
class Program { static void Main(string[] args) { Father father = new Father(); TestT(father); Childern childern = new Childern(); TestT(childern); Object obj = new Object(); //TestT(obj);//报错 Console.ReadKey(); } public static void TestT<T>(T t) where T : Father { Console.WriteLine(t.GetType()); } } class Father { } class Childern:Father { }
5.
class Program { static void Main(string[] args) { TestClass testClass = new TestClass(); TestT(testClass); TestClass2 testClass2 = new TestClass2(123); //TestT(testClass2);//报错 Console.ReadKey(); } public static void TestT<T>(T t) where T : new() { Console.WriteLine(t.GetType()); } } class TestClass { } class TestClass2 { public TestClass2(int num) { } }
6.
class Program { static void Main(string[] args) { TestClass testClass = new TestClass(); TestClass2 testClass2 = new TestClass2(); TestT(testClass2,testClass); Console.ReadKey(); } public static void TestT<T1,T2>(T1 t,T2 t2) where T1 : T2 { Console.WriteLine(t.GetType()); } } class TestClass { } class TestClass2 : TestClass { public TestClass2() { } }
内容总结
以上是互联网集市为您收集整理的C#泛型约束全部内容,希望文章能够帮你解决C#泛型约束所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。