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


    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();
            }
        }
    }
  • 相关阅读:
    相似矩阵
    特征值和特征向量
    非齐次方程组的通解
    线性方程组解的性质和结构、基础解系
    高斯消元法求齐次线性方程的通解
    从零开始学 Web 之 HTML(三)表单
    从零开始学Web之HTML(二)标签、超链接、特殊符号、列表、音乐、滚动、head等
    从零开始学 Web 之 HTML(一)认识前端
    JavaScript基础(一)概述
    如何恢复windows的exe文件的默认打开方式
  • 原文地址:https://www.cnblogs.com/tofight/p/16169862.html
Copyright © 2020-2023  润新知