Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking static methods containing Generic Parameters using Reflection [duplicate]

While executing the following code i gets this error "Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true."

class Program
{
    static void Main(string[] args)
    {
        MethodInfo MI = typeof(MyClass).GetMethod("TestProc");
        MI.MakeGenericMethod(new [] {typeof(string)});
        MI.Invoke(null, new [] {"Hello"});
    }
}

class MyClass
{
    public static void TestProc<T>(T prefix) 
    {
        Console.WriteLine("Hello");
    }
}

The above code is just a scaled version of the actual problem i am facing. Please help.

like image 403
AbrahamJP Avatar asked Jun 16 '10 10:06

AbrahamJP


2 Answers

You are calling MethodInfo.MakeGenericMethod but throwing away the return value. The return value itself is the method you want to Invoke :

MethodInfo genericMethod = MI.MakeGenericMethod(new[] { typeof(string) });
genericMethod.Invoke(null, new[] { "Hello" });
like image 128
AakashM Avatar answered Oct 03 '22 17:10

AakashM


The only problem with the code that you post is:

MI.MakeGenericMethod(new [] {typeof(string)}); 

Should be

MI = MI.MakeGenericMethod(new [] {typeof(string)}); 

You're not grabbing a reference to the 'baked' generic.

like image 42
Andras Zoltan Avatar answered Oct 03 '22 18:10

Andras Zoltan