经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C# » 查看文章
C# -- 泛型的使用
来源:cnblogs  作者:在代码的世界里游走  时间:2018/12/24 10:43:15  对本文有异议

C# -- 泛型的使用

1. 使用泛型

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. int number = 100;
  6. string str = "Hello";
  7. //使用泛型方式1,传入参数类型和参数
  8. MyTest<int>(number);
  9. MyTest<string>(str);
  10. //使用泛型方式2,传入参数-->编译器会根据参数推断出参数的类型
  11. MyTest(number);
  12. MyTest(str);
  13. Console.ReadKey();
  14. }
  15. public static void MyTest<T>(T t)
  16. {
  17. Console.WriteLine("{0} 的类型是{1}",t.ToString(),t.GetType());
  18. }
  19. }

运行结果:

 

2. 泛型约束

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. int number = 20181223;
  6. string str = "Hello,2018-12-23";
  7. //MyTest1传入参数类型必须是引用类型,否则会编译时报错
  8. MyTest1<string>(str);
  9. //MyTest2传入参数类型必须是值类型,否则会编译时报错
  10. MyTest2<int>(number);
  11. Console.ReadKey();
  12. }
  13. //限定传入的参数类型是引用类型
  14. public static void MyTest1<T>(T t) where T:class
  15. {
  16. Console.WriteLine("{0} 的类型是{1}",t.ToString(),t.GetType());
  17. }
  18. //限定传入的参数类型是值类型
  19. public static void MyTest2<T>(T t) where T:struct
  20. {
  21. Console.WriteLine("{0} 的类型是{1}", t.ToString(), t.GetType());
  22. }
  23. }

运行结果:

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号