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 }
  • 相关阅读:
    机器学习:SVM(核函数、高斯核函数RBF)
    机器学习:SVM(非线性数据分类:SVM中使用多项式特征和核函数SVC)
    LeetCode566. Reshape the Matrix
    LeetCode 128. Longest Consecutive Sequence
    # 线程安全 & 线程安全函数 & 线程不安全函数
    Linux进程状态
    C++ 4种强制类型转换
    TCP超时重传、滑动窗口、拥塞控制、快重传和快恢复
    LeetCode 69. Sqrt(x)
    LeetCode543. Diameter of Binary Tree
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/11980016.html
Copyright © 2011-2022 走看看