• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
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();
        }
    }
}

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
VSTO:使用C#开发Excel、Word【1】发布时间:2022-07-10
下一篇:
[Transfer]DataList自定义分页(C#)发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap