zoukankan      html  css  js  c++  java
  • 使用反射操作泛型类、泛型方法

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

     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 }
  • 相关阅读:
    eclipse报错:发现了以元素 'd:skin' 开头的无效内容。此处不应含有子元素
    深入解析_Android的自定义布局
    RSA算法加密解密
    android版本
    TabHost+RadioGroup搭建基础布局
    android横竖屏控制
    一大波静态方法
    有时候
    简单的dialog菜单
    mongodb学习(三)——函数使用的小技巧
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/11980016.html
Copyright © 2011-2022 走看看