Call a non-generic method with generic arguments defined in a generic class

Here is my problem;

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

What I've done:

 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: Limited-bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.

If I try to create a generic method, it will end again with an exception: MakeGenericMethod can only be called for a method that has the MethodBase.IsGenericMethodDefinition property set.

How do I call a method?

+6
source share
1 answer

You are calling GetMethod on the wrong object. Call it using the associated generic type and it should work. Here is a complete sample that works correctly:

 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); } } } 
+11
source

Source: https://habr.com/ru/post/904851/


All Articles