• C# 泛型详解(泛型类,方法,接口,委托,约束,反射 )


    目录

    一、什么是泛型

    二、为什么要用泛型

    三、泛型和Object类型的区别

    四、泛型类

    五、泛型方法

    六、泛型接口

    七、泛型委托

    八、泛型约束

    九、泛型配合反射

    结束


    一、什么是泛型

    先看一段介绍

    泛型(Generic),是将不确定的类型预先定义下来的一种C#高级语法,我们在使用一个类,接口或者方法前,不知道用户将来传什么类型,或者我们写的类,接口或方法相同的代码可以服务不同的类型,就可以定义为泛型。这会大大简化我们的代码结构,同时让后期维护变得容易。

    泛型很适用于集合,我们常见的泛型集合有:List,Dictionary等等(T,K,V就代表不确定的类型,它是一种类型占位符),无一不是利用的泛型这一特性,若没有泛型,我们会多出很多重载方法,以解决类型不同,但是执行逻辑相同的情况。

    看看上面这一堆介绍看着都想睡觉了,没办法,CSDN要求文字个数不够就不给推荐,估计这些简介也没几个人会去仔细看的哈,哈哈哈。

    废话一大堆,那么泛型到底长啥样?,看到下面代码中的 “T” 没有,那就是泛型。

    1. namespace 泛型
    2. {
    3. class Program
    4. {
    5. static void Main(string[] args)
    6. {
    7. Test<string>();
    8. Console.ReadKey();
    9. }
    10. static void Test<T>()
    11. {
    12. Console.WriteLine(typeof(T).FullName);
    13. }
    14. }
    15. }

    输出:System.String

    你可能会问,这个 “T” 就是泛型啊?把 “T” 改成鸡,那鸡不也是泛型了?

    1. namespace 泛型
    2. {
    3. class Program
    4. {
    5. static void Main(string[] args)
    6. {
    7. Test<string>();
    8. Console.ReadKey();
    9. }
    10. static void Test<鸡>()
    11. {
    12. Console.WriteLine("鸡你太美");
    13. }
    14. }
    15. }

    是的,没错,输出:鸡你太美

    二、为什么要用泛型

    先看一个例子

    1. namespace 泛型
    2. {
    3. class Program
    4. {
    5. static void Main(string[] args)
    6. {
    7. int result = Test.Add(3, 4);
    8. Console.WriteLine(result);
    9. Console.ReadKey();
    10. }
    11. }
    12. public class Test
    13. {
    14. public static int Add(int x, int y)
    15. {
    16. return x + y;
    17. }
    18. public static int Add(string x, string y)
    19. {
    20. return int.Parse(x) + int.Parse(y);
    21. }
    22. }
    23. }

    比如,我们需要封装一个加法的算法,但是传入的类型,可能有 int 类型,也可能有 string 类型,还可能有其他的类型,但是每多一种类型,你就要多加一个方法,非常的麻烦,臃肿。

    那么有没有方法来解决这个问题呢,于是后面C#2.0中,就有了泛型这个概念,它并不是语法糖,看字面意思像 “泛滥的类型” 的意思。

    那么下面就用泛型的方式来封装一下这个加法运算。

    注意一下写法,在 Add 后面要加上 这句,不然会报错。

    正确方式

    下面是封装加法的完整代码

    1. public class Test
    2. {
    3. public static int Add<T>(T x,T y)
    4. {
    5. try
    6. {
    7. return int.Parse(x.ToString()) + int.Parse(y.ToString());
    8. }
    9. catch (Exception ex)
    10. {
    11. Console.WriteLine(ex.Message);
    12. }
    13. return -1;
    14. }
    15. }

    测试第一种

    1. class Program
    2. {
    3. static void Main(string[] args)
    4. {
    5. int result = Test.Add("3", "4");
    6. Console.WriteLine(result);
    7. Console.ReadKey();
    8. }
    9. }

    输出:7

    测试第二种

    1. class Program
    2. {
    3. static void Main(string[] args)
    4. {
    5. int result = Test.Add(4, 5);
    6. Console.WriteLine(result);
    7. Console.ReadKey();
    8. }
    9. }

    输出:9

    三、泛型和Object类型的区别

    看了上面的案例,你会觉得,泛型是不是 Object 类型不是也差不多?下面是一些介绍:

    C# 中 Object 是一切类型的基类,可以用来表示所有类型,而泛型是指将类型参数化以达到代码复用提高软件开发工作效率的一种数据类型。

    你可以将泛型理解成替换,在使用的时候将泛型参数替换成具体的类型,这个过程是在编译的时候进行的,使用泛型编译器依然能够检测出类型错误。泛型不用拆箱装箱。

    而 Object 表示其他类型是通过类型转换来完成的,而所有类型转化为 Object 类型都是合法的,所以即使你先将 Object 对象赋值为一个整数再赋值为一个字符串,编译器都认为是合法的。

    Object 类型

    > 优点:
    > 1. object类型可以用来引用任何类型的实例;
    > 2. object类型可以存储任何类型的值;
    > 3. 可以定义object类型的参数;
    > 4. 可以把object作为返回类型。

    > 缺点:
    > 1. 会因为程序员没有记住使用的类型而出错,造成类型不兼容;
    > 2. 值类型和引用类型的互化即装箱拆箱使系统性能下降。

    泛型,Object 类型,var 类型,这三种类型,看着很类似,但其实泛型的作用更不止如此,还有泛型类,泛型方法,泛型接口,泛型约束等,下面分别来介绍这几个功能

    四、泛型类

    泛型类是指这个类的某些字段的类型是不确定的,只有在构造的时候才能确定下的类,泛型类一般在数据结构中用的比较多,比如 C# 自带的 List,Dictionary 等,我也写过自定义 List 相关的帖子,有兴趣的可以去看下

    C# 自定义List_熊思宇的博客-CSDN博客_c#定义list

    1.泛型类案例

    下面看一个例子

    1. namespace 泛型
    2. {
    3. class Program
    4. {
    5. static void Main(string[] args)
    6. {
    7. Test<int> test = new Test<int>();
    8. test.Add(1);
    9. test.Add(3);
    10. Console.WriteLine(test.Count);
    11. Console.ReadKey();
    12. }
    13. }
    14. public class Test<T>
    15. {
    16. private List list = new List();
    17. public int Count => list.Count;
    18. public void Add(T t)
    19. {
    20. if(t != null)
    21. list.Add(t);
    22. }
    23. }
    24. }

    运行后输出:2

    Test 类此时并没有添加任何的约束,这个是不推荐的,至少应该加一个,如下

    1. public class Test<T> where T : new()
    2. {
    3. private List list = new List();
    4. public int Count => list.Count;
    5. public void Add(T t)
    6. {
    7. if(t != null)
    8. list.Add(t);
    9. }
    10. }

    关于泛型约束,在后面的章节中会有详细的介绍。

    2.泛型类继承

    泛型类型继承写法:

    1. public class Test1<T>
    2. {
    3. }
    4. public class Test2<T> : Test1<T>
    5. {
    6. }

    指定基类的类型写法:

    1. public class Test1<T>
    2. {
    3. }
    4. public class Test2<T> : Test1<int>
    5. {
    6. }

    关于泛型类的继承,后面我再单独写文章进行介绍吧

    五、泛型方法

    泛型方法是指通过泛型来约束方法中的参数类型,如果没有泛型,每次方法中的参数类型都是固定的,不能随意更改,在使用泛型后,方法中的数据类型则有指定的泛型来约束,即可以根据提供的泛型来传递不同类型的参数。

    泛型方法的返回类型和参数类型都可以使用泛型。如下:

    1. public static T GetT<T>(T a)
    2. {
    3. return a;
    4. }

    泛型方法同样可以使用泛型约束,只是泛型方法中的 T 只能用在方法内部和返回值,而泛型类中的 T 可以应用于整个类的字段和方法。

    1. public class Test
    2. {
    3. public void Add<T>(T t) where T : new()
    4. {
    5. List list = new List();
    6. if (t != null) list.Add(t);
    7. }
    8. }

    如果要对 T 类型作一些操作,则需要用到反射。

    六、泛型接口

    泛型接口如下

    1. public interface IFace<T>
    2. {
    3. void SayHi(T msg);
    4. }

    同样的,泛型接口也可以使用泛型约束

    1. public interface IFace<T> where T : new()
    2. {
    3. void SayHi(T msg);
    4. }

    实现泛型接口有两种情况

    1. ///
    2. /// 1.普通类实现泛型接口
    3. ///
    4. public class MyClass1 : IFace<string>
    5. {
    6. public void SayHi(string msg)
    7. {
    8. Console.WriteLine(msg);
    9. }
    10. }
    11. ///
    12. /// 2.泛型类继承泛型接口
    13. ///
    14. ///
    15. public class MyClass2<T> : IFace<T>
    16. {
    17. public void SayHi(T msg)
    18. {
    19. Console.WriteLine(msg);
    20. }
    21. }

    案例

    1. namespace 泛型
    2. {
    3. class Program
    4. {
    5. static void Main(string[] args)
    6. {
    7. IFace face = new Test();
    8. face.SayHi(new Msg());
    9. Console.ReadKey();
    10. }
    11. }
    12. public interface IFace<T> where T : new()
    13. {
    14. void SayHi(T msg);
    15. }
    16. public class Test : IFace<Msg>
    17. {
    18. public void SayHi(Msg msg)
    19. {
    20. Console.WriteLine(msg.MyName);
    21. }
    22. }
    23. public class Msg
    24. {
    25. public string MyName = "张三";
    26. }
    27. }

    输出:张三

    七、泛型委托

    泛型委托和普通委托差别不大,只是参数由具体类型变成了 "T"

    public delegate void MyDelegate<T>(T args); 

    案例

    1. namespace 泛型
    2. {
    3. class Program
    4. {
    5. delegate void MyDelegate<T>(T args);
    6. static void Main(string[] args)
    7. {
    8. MyDelegate<string> myDelegate = SayHi;
    9. myDelegate("哈喽");
    10. Console.ReadKey();
    11. }
    12. static void SayHi(string msg)
    13. {
    14. Console.WriteLine(msg);
    15. }
    16. }
    17. }

    输出:哈喽

    八、泛型约束

    泛型约束就是对 “T” 类型的数据做一定的限制,防止在运用过程中,做一些违规的操作,来保证数据的安全。

    六种类型的约束:

    T:结构

    类型参数必须是值类型。可以指定除 Nullable 以外的任何值类型。有关更多信息,请参见使用可空类型(C# 编程指南)。

    T:类

    类型参数必须是引用类型,包括任何类、接口、委托或数组类型。

    T:new()

    类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时,new() 约束必须最后指定。

    T:<基类名>

    类型参数必须是指定的基类或派生自指定的基类。

    T:<接口名称>

    类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。

    T:U

    为 T 提供的类型参数必须是为 U 提供的参数或派生自为 U 提供的参数。这称为裸类型约束。

    案例

    1. namespace 泛型
    2. {
    3. class Program
    4. {
    5. static void Main(string[] args)
    6. {
    7. Console.ReadKey();
    8. }
    9. }
    10. ///
    11. /// 泛型接口
    12. ///
    13. ///
    14. public interface IFace<T>
    15. {
    16. void SayHi(T msg);
    17. }
    18. ///
    19. /// 泛型约束
    20. ///
    21. public class MyClass1<T, K, V, W, X,Y>
    22. where T : struct //约束 T 必须是值类型
    23. where K : class //约束 K 必须是引用类型
    24. where V : IFace<T> //约束 V 必须实现 IFace 接口
    25. where W : K //约束 W 必须是 K 类型,或者是 K 类型的子类
    26. where X : class, new() //约束 X 必须是引用类型,并且有一个无参数的构造函数,当有多个约束时,new()必须写在最后
    27. where Y : MyClass2 //约束 Y 必须是 MyClass2 类型,或者继承于 MyClass2 类
    28. {
    29. public void Add(T num)
    30. {
    31. Console.WriteLine(num);
    32. }
    33. }
    34. public class MyClass2
    35. {
    36. }
    37. }

    这个案例,几乎介绍了所有的泛型约束的使用方法,有兴趣的可以亲自动手写一写。

    九、泛型配合反射

    现在有一个需求,用户修改个人资料,在提交这里必须要判断是否有修改内容,如果没有修改,点击提交按钮则不提交,那要怎么判断呢?

    有人可能会说,用 if...else 去判断就好了,可以这么写没错,但资料如果有几百个地方改了,不会还用 if...else 吧,那整篇代码全是 if...else 了,就像我同事开玩笑一样:“我不会高数,我只会写 if...else...”

    下面这个案例就教你如何来解决这个问题。

    代码

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Reflection;
    5. using System.Text;
    6. using System.Threading.Tasks;
    7. namespace 泛型
    8. {
    9. class Program
    10. {
    11. static void Main(string[] args)
    12. {
    13. Test test1 = new Test();
    14. test1.Names = "张三";
    15. test1.Age = 24;
    16. test1.Height = 179.9f;
    17. Test test2 = new Test();
    18. test2.Names = "李四";
    19. test2.Age = 31;
    20. test2.Height = 163.4f;
    21. bool result = CompareType(test1, test2);
    22. Console.WriteLine("是否相同:" + result);
    23. Console.ReadKey();
    24. }
    25. ///
    26. /// 比较--两个类型一样的实体类对象的值
    27. ///
    28. ///
    29. /// 返回true表示两个对象的数据相同,返回false表示不相同
    30. public static bool CompareType<T>(T oneT, T twoT)
    31. {
    32. bool result = true;//两个类型作比较时使用,如果有不一样的就false
    33. Type typeOne = oneT.GetType();
    34. Type typeTwo = twoT.GetType();
    35. //如果两个T类型不一样 就不作比较
    36. if (!typeOne.Equals(typeTwo)) { return false; }
    37. PropertyInfo[] pisOne = typeOne.GetProperties(); //获取所有公共属性(Public)
    38. PropertyInfo[] pisTwo = typeTwo.GetProperties();
    39. //如果长度为0返回false
    40. if (pisOne.Length <= 0 || pisTwo.Length <= 0)
    41. {
    42. return false;
    43. }
    44. //如果长度不一样,返回false
    45. if (!(pisOne.Length.Equals(pisTwo.Length))) { return false; }
    46. //遍历两个T类型,遍历属性,并作比较
    47. for (int i = 0; i < pisOne.Length; i++)
    48. {
    49. //获取属性名
    50. string oneName = pisOne[i].Name;
    51. string twoName = pisTwo[i].Name;
    52. //获取属性的值
    53. object oneValue = pisOne[i].GetValue(oneT, null);
    54. object twoValue = pisTwo[i].GetValue(twoT, null);
    55. //比较,只比较值类型
    56. if ((pisOne[i].PropertyType.IsValueType || pisOne[i].PropertyType.Name.StartsWith("String")) && (pisTwo[i].PropertyType.IsValueType || pisTwo[i].PropertyType.Name.StartsWith("String")))
    57. {
    58. if (oneName.Equals(twoName))
    59. {
    60. if (oneValue == null)
    61. {
    62. if (twoValue != null)
    63. {
    64. result = false;
    65. break; //如果有不一样的就退出循环
    66. }
    67. }
    68. else if (oneValue != null)
    69. {
    70. if (twoValue != null)
    71. {
    72. if (!oneValue.Equals(twoValue))
    73. {
    74. result = false;
    75. break; //如果有不一样的就退出循环
    76. }
    77. }
    78. else if (twoValue == null)
    79. {
    80. result = false;
    81. break; //如果有不一样的就退出循环
    82. }
    83. }
    84. }
    85. else
    86. {
    87. result = false;
    88. break;
    89. }
    90. }
    91. else
    92. {
    93. //如果对象中的属性是实体类对象,递归遍历比较
    94. bool b = CompareType(oneValue, twoValue);
    95. if (!b) { result = b; break; }
    96. }
    97. }
    98. return result;
    99. }
    100. }
    101. public class Test
    102. {
    103. public string Names { get; set; }
    104. public int Age { get; set; }
    105. public float Height { get; set; }
    106. }
    107. }

    输出:是否相同:False

    将这两个 Test 对象的值改为一样试试

    1. static void Main(string[] args)
    2. {
    3. Test test1 = new Test();
    4. test1.Names = "张三";
    5. test1.Age = 24;
    6. test1.Height = 179.9f;
    7. Test test2 = new Test();
    8. test2.Names = "张三";
    9. test2.Age = 24;
    10. test2.Height = 179.9f;
    11. bool result = CompareType(test1, test2);
    12. Console.WriteLine("是否相同:" + result);
    13. Console.ReadKey();
    14. }

    输出:是否相同:True

    可以看到,输出结果是对的

    结束

    如果这个帖子对你有用,欢迎 关注 + 点赞 + 留言,谢谢

    end

  • 相关阅读:
    法国博士后招聘|国家健康与医学研究院(INSERM)-计算化学
    实现动态页面的技术Servlet
    计算机毕业设计ssm+vue基本微信小程序的奶茶点单系统
    【李航统计学习笔记】第七章:支持向量机
    小程序页面导航和页面事件
    Linux选择题笔记
    数学建模十大算法03—线性规划、整数规划、非线性规划、多目标规划
    scanf跳过第一个输入读入第二个输入,咋做?
    Python机器学习实战-特征重要性分析方法(1):排列重要性(附源码和实现效果)
    Eureka(注册中心)
  • 原文地址:https://blog.csdn.net/qq_38693757/article/details/126625961