简体   繁体   中英

Invoke a non generic method with generic arguments defined in a generic class

Here is my issue;

public class MyClass<T>
{
   public void DoSomething(T obj)
   {
      ....
   }
}

What I did is:

var classType = typeof(MyClass<>);
Type[] classTypeArgs = { typeof(T) };
var genericClass = classType.MakeGenericType(classTypeArgs);
var classInstance = Activator.CreateInstance(genericClass);
var method = classType.GetMethod("DoSomething", new[]{typeof(T)});
method.Invoke(classInstance, new[]{"Hello"});

In the above case the exception I get is: Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.

If I try to make the method generic it fails again with an exception: MakeGenericMethod may only be called on a method for which MethodBase.IsGenericMethodDefinition is true.

How should I invoke the method?

You are calling GetMethod on the wrong object. Call it with the bound generic type and it should work. Here is a complete sample which works properly:

using System;
using System.Reflection;

internal sealed class Program
{
    private static void Main(string[] args)
    {
        Type unboundGenericType = typeof(MyClass<>);
        Type boundGenericType = unboundGenericType.MakeGenericType(typeof(string));
        MethodInfo doSomethingMethod = boundGenericType.GetMethod("DoSomething");
        object instance = Activator.CreateInstance(boundGenericType);
        doSomethingMethod.Invoke(instance, new object[] { "Hello" });
    }

    private sealed class MyClass<T>
    {
        public void DoSomething(T obj)
        {
            Console.WriteLine(obj);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM