zoukankan      html  css  js  c++  java
  • 使用C#反射中的MakeGenericType函数,来为泛型方法和泛型类指定(泛型的)类型

    using System;
    using System.Reflection;
    
    namespace RFTest
    {
        //类ReflectionTest中定义了一个泛型函数DisplayType和泛型类MyGenericClass
        class ReflectionTest
        {
            //泛型类MyGenericClass有个静态函数DisplayNestedType
            public class MyGenericClass<T>
            {
                public static void DisplayNestedType()
                {
                    Console.WriteLine(typeof(T).ToString());
                }
            }
    
            public void DisplayType<T>()
            {
                Console.WriteLine(typeof(T).ToString());
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                ReflectionTest rt = new ReflectionTest();
    
                MethodInfo mi = rt.GetType().GetMethod("DisplayType");//先获取到DisplayType<T>的MethodInfo反射对象
                mi.MakeGenericMethod(new Type[] { typeof(string) }).Invoke(rt, null);//然后使用MethodInfo反射对象调用ReflectionTest类的DisplayType<T>方法,这时要使用MethodInfo的MakeGenericMethod函数指定函数DisplayType<T>的泛型类型T
    
                Type myGenericClassType = rt.GetType().GetNestedType("MyGenericClass`1");//这里获取MyGenericClass<T>的Type对象,注意GetNestedType方法的参数要用MyGenericClass`1这种格式才能获得MyGenericClass<T>的Type对象
                myGenericClassType.MakeGenericType(new Type[] { typeof(float) }).GetMethod("DisplayNestedType", BindingFlags.Static | BindingFlags.Public).Invoke(null, null);
                //然后用Type对象的MakeGenericType函数为泛型类MyGenericClass<T>指定泛型T的类型,比如上面我们就用MakeGenericType函数将MyGenericClass<T>指定为了MyGenericClass<float>,然后继续用反射调用MyGenericClass<T>的DisplayNestedType静态方法
    
                Console.ReadLine();
            }
        }
    }
  • 相关阅读:
    机器学习理论基础
    Python 2/3 安装与运行环境设置
    connect/express 的参考
    Koa2 的安装运行记录(二)
    iOS如何才能在招聘中表现得靠谱?
    游戏本地化不止是翻译,还有……
    IOS 判断当前UIViewController 是否正在显示
    获取iOS应用中当前处于Activity状态的ViewController
    APP UI设计趋势:为好设计而动
    实现ios后台缩略图模糊的一种方法
  • 原文地址:https://www.cnblogs.com/sjqq/p/9634517.html
Copyright © 2011-2022 走看看