c#反射操作泛型类/泛型方法

FileName.cs文件
namespace ZHAOXI.DBHlper
{
    class FileName
    {
        public void Show<T, W, Q>(T t, W w, Q q)
        {
            Console.WriteLine("这里是" + this.GetType().Name + " " + "普通类里面的泛型方法: t " + t + " w " + w + " q " + q);
        }
    }

    class Gencts<T, W, Q>
    {
        public void Show(T t, W w, Q q)
        {
            Console.WriteLine("这里是" + this.GetType().Name + " " + "泛型类里面的泛型方法: t " + t + " w " + w + " q " + q);
        }
    }

    class Mguntpund<T>
    {
        public void Show<W, Q>(T t, W w, Q q)
        {
            Console.WriteLine("这里是" + this.GetType().Name + " " + "泛型类里面的泛型方法第二种情况: t " + t + " w " + w + " q " + q);
        }
    }
}

Program.cs类

using System.Reflection;
//反射调用泛型类泛型方法
Assembly assembly1 = Assembly.LoadFrom("ZHAOXI.DBHlper.dll");

//反射调用普通类里面的泛型方法
Type fileName = assembly1.GetType("ZHAOXI.DBHlper.FileName");
MethodInfo method = fileName.GetMethod("Show");
MethodInfo constructedMethod = method.MakeGenericMethod(new Type[] { typeof(string), typeof(int), typeof(DateTime) });
object obj1 = Activator.CreateInstance(fileName);
constructedMethod.Invoke(obj1, new object[] { "龙卷风摧毁停车场", 10086, DateTime.Now });

//反射调用泛型类里面的泛型方法
Type gencts = assembly1.GetType("ZHAOXI.DBHlper.Gencts`3");
Type makeGenericType = gencts.MakeGenericType(new Type[] { typeof(int), typeof(string), typeof(DateTime) });
MethodInfo constructedMethod1 = makeGenericType.GetMethod("Show");
object obj2 = Activator.CreateInstance(makeGenericType);
constructedMethod1.Invoke(obj2, new object[] { 10086, "龙卷风摧毁停车场", DateTime.Now });

//反射调用泛型类第二种情况
Type mguntpund = assembly1.GetType("ZHAOXI.DBHlper.Mguntpund`1");
Type mguntpundType = mguntpund.MakeGenericType(new Type[] { typeof(string) });
MethodInfo mguntpundMethod = mguntpundType.GetMethod("Show");
MethodInfo mguntpundInfo = mguntpundMethod.MakeGenericMethod(new Type[] {typeof(DateTime),typeof(int)});
object obj3 = Activator.CreateInstance(mguntpundType);
mguntpundInfo.Invoke(obj3, new object[] {"龙卷风摧毁停车场", DateTime.Now, 10086});

Console.ReadKey();

允许结果

 

posted @ 2024-10-09 14:14  龙卷风吹毁停车场  阅读(14)  评论(0编辑  收藏  举报