首页 > 其他 > 详细

反射获取泛型类、泛型方法

时间:2019-12-04 00:18:52      阅读:101      评论:0      收藏:0      [点我收藏+]

反射获取泛型类、泛型方法

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

 

反射获取泛型类、泛型方法

原文:https://www.cnblogs.com/fanfan-90/p/11980016.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!