如何通过反射调用泛型方法

时间:2009-12-21 16:52:26

标签: c# reflection generics

是否可以使用反射调用具有“explict type argument”<S>定义的方法 例如oObject.Cast<S>()

在哪里:

IList <P> oObject = new List <P>();

我试过

oObject.getType().InvokeMember( "Cast", BindingFlags.InvokeMethod, null, oObject, null)

但它不起作用,有人知道为什么吗?


这是完整的测试代码,但仍然不起作用。最后一行总是产生异常。是否有可能使其有效?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace reflection_tester
{
    class CBase
    {
        public string Ja = "I am the base";
    }

    class MyClass01 : CBase
    {
        public string _ID;

        public string ID
        {
            get { return _ID; }
            set { _ID = value; }
        }
    }

    class Program
    {

        public static object wrapper()
        {
            //return a list of classes MyClass01

            IList<MyClass01> lstClass01 = new List<MyClass01>();

            MyClass01 oClass01a = new MyClass01();
            oClass01a.ID = "1";

            MyClass01 oClass01b = new MyClass01();
            oClass01b.ID = "2";

            lstClass01.Add(oClass01a);
            lstClass01.Add(oClass01b);

            return lstClass01;
        }

        static void Main(string[] args)
        {

            MyClass01 oMy1 = new MyClass01();
            oMy1._ID = "1";

            MyClass01 oMy2 = new MyClass01();
            oMy2._ID = "3";

            IList<MyClass01> oListType01 = new List<MyClass01>();

            oListType01.Add(oMy1);
            oListType01.Add(oMy2);

            object oObjectType = new object();

            oObjectType = oListType01;

            /* this works */
            IEnumerable<CBase> enumList = oListType01.Cast<CBase>();

            MethodInfo mInfo = typeof(System.Linq.Enumerable).GetMethod("Cast", new[] { typeof(System.Collections.IEnumerable) }).MakeGenericMethod(typeof(CBase));

            /* this does not work, why ? throws exception */
            IEnumerable<CBase> enumThroughObject = (IEnumerable<CBase>)mInfo.Invoke(oObjectType, null);

            return;
        }
    }
}

2 个答案:

答案 0 :(得分:13)

Cast扩展方法存在于Enumerable类中,您需要调用MakeGenericMethod:

typeof(System.Linq.Enumerable)
    .GetMethod("Cast", new []{typeof(System.Collections.IEnumerable)})
    .MakeGenericMethod(typeof(S))
    .Invoke(null, new object[] { oObjectType })

更新:由于该方法是静态的,因此调用的第一个参数应为null

答案 1 :(得分:0)

我认为你正在寻找Type.MakeGenericType

相关问题