Use Reflection to call the generic method of an instance of an object with a signature: SomeObject.SomeGenericInstanceMethod <T> (argument T)

How do I call SomeObject.SomeGenericInstanceMethod<T>(T arg) ?

There are some reports of calls to common methods, but not quite like that. The problem is that the method argument parameter is limited to the general parameter.

I know that if the signature was instead

SomeObject.SomeGenericInstanceMethod<T>(string arg)

then I could get MethodInfo with

typeof (SomeObject).GetMethod("SomeGenericInstanceMethod", new Type[]{typeof (string)}).MakeGenericMethod(typeof(GenericParameter))

So, how do I get the MethodInfo method when regular arguments have a common type? Thank you

In addition, there may or may not be type restrictions for the general parameter.

+2
generics reflection c #
source share
2 answers

You do it the exact same way.

When you call MethodInfo.Invoke, you pass all the arguments to object[] anyway, so you don't need to know the types at compile time.

Example:

 using System; using System.Reflection; class Test { public static void Foo<T>(T item) { Console.WriteLine("{0}: {1}", typeof(T), item); } static void CallByReflection(string name, Type typeArg, object value) { // Just for simplicity, assume it public etc MethodInfo method = typeof(Test).GetMethod(name); MethodInfo generic = method.MakeGenericMethod(typeArg); generic.Invoke(null, new object[] { value }); } static void Main() { CallByReflection("Foo", typeof(object), "actually a string"); CallByReflection("Foo", typeof(string), "still a string"); // This would throw an exception // CallByReflection("Foo", typeof(int), "oops"); } } 
+11
source share

You do it the same way, but pass in an instance of your object:

 typeof (SomeObject).GetMethod( "SomeGenericInstanceMethod", yourObject.GetType()) // Or typeof(TheClass), // or typeof(T) if you're in a generic method .MakeGenericMethod(typeof(GenericParameter)) 

The MakeGenericMethod method only requires you to specify the parameters of the generic type, not the arguments of the method.

You will pass the arguments later when you call the method. However, at the moment they are passed as an object , so this does not matter again.

+2
source share

All Articles