Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a generic method through reflection [duplicate]

is it possible to call with reflection a method with "explict type argument" <S> definition
e.g. oObject.Cast<S>() ?

where is:

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

I tried with

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

but it does not work, does anyone know why?


Here is the complete test code but still it does not work. The last line produce always exception. Is it possible to make it work ?

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;
        }
    }
}
like image 472
milan Avatar asked Dec 21 '09 16:12

milan


1 Answers

The Cast extension method lives on the class Enumerable, and you need to call MakeGenericMethod:

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

update: Because the method is static, the first parameter to Invoke should be null

like image 55
Rob Fonseca-Ensor Avatar answered Nov 14 '22 23:11

Rob Fonseca-Ensor