使用C#反射中的MakeGenericType函数,来为泛型方法和泛型类指定(泛型的)类型

不念不忘少年蓝@ 2022-06-09 04:09 187阅读 0赞

C#反射中的MakeGenericType函数可以用来指定泛型方法和泛型类的具体类型,方法如下面代码所示这里就不多讲了,详情看下面代码一切就清楚了:

复制代码

  1. using System;
  2. using System.Reflection;
  3. namespace RFTest
  4. {
  5. //类ReflectionTest中定义了一个泛型函数DisplayType和泛型类MyGenericClass
  6. class ReflectionTest
  7. {
  8. //泛型类MyGenericClass有个静态函数DisplayNestedType
  9. public class MyGenericClass<T>
  10. {
  11. public static void DisplayNestedType()
  12. {
  13. Console.WriteLine(typeof(T).ToString());
  14. }
  15. }
  16. public void DisplayType<T>()
  17. {
  18. Console.WriteLine(typeof(T).ToString());
  19. }
  20. }
  21. class Program
  22. {
  23. static void Main(string[] args)
  24. {
  25. ReflectionTest rt = new ReflectionTest();
  26. MethodInfo mi = rt.GetType().GetMethod("DisplayType");//先获取到DisplayType<T>的MethodInfo反射对象
  27. mi.MakeGenericMethod(new Type[] { typeof(string) }).Invoke(rt, null);//然后使用MethodInfo反射对象调用ReflectionTest类的DisplayType<T>方法,这时要使用MethodInfo的MakeGenericMethod函数指定函数DisplayType<T>的泛型类型T
  28. Type myGenericClassType = rt.GetType().GetNestedType("MyGenericClass`1");//这里获取MyGenericClass<T>的Type对象,注意GetNestedType方法的参数要用MyGenericClass`1这种格式才能获得MyGenericClass<T>的Type对象
  29. myGenericClassType.MakeGenericType(new Type[] { typeof(float) }).GetMethod("DisplayNestedType", BindingFlags.Static | BindingFlags.Public).Invoke(null, null);
  30. //然后用Type对象的MakeGenericType函数为泛型类MyGenericClass<T>指定泛型T的类型,比如上面我们就用MakeGenericType函数将MyGenericClass<T>指定为了MyGenericClass<float>,然后继续用反射调用MyGenericClass<T>的DisplayNestedType静态方法
  31. Console.ReadLine();
  32. }
  33. }
  34. }

发表评论

表情:
评论列表 (有 0 条评论,187人围观)

还没有评论,来说两句吧...

相关阅读