使用Reflection通过签名调用对象实例上的generics方法:SomeObject.SomeGenericInstanceMethod (T参数)

如何调用SomeObject.SomeGenericInstanceMethod(T arg)

有一些关于调用generics方法的post,但不完全像这个。 问题是method参数被约束为generics参数。

我知道如果签名是相反的

SomeObject.SomeGenericInstanceMethod(string arg)

然后我可以得到MethodInfo

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

那么,当常规参数是generics类型时,如何获取MethodInfo? 谢谢!

此外,generics参数可能有也可能没有类型约束。

你完全以同样的方式做到这一点。

当您调用MethodInfo.Invoke时,无论如何都会传递object[]中的所有参数,因此您不必在编译时知道类型。

样品:

 using System; using System.Reflection; class Test { public static void Foo(T item) { Console.WriteLine("{0}: {1}", typeof(T), item); } static void CallByReflection(string name, Type typeArg, object value) { // Just for simplicity, assume it's 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"); } } 

您以完全相同的方式执行此操作,但传递对象的实例:

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

MakeGenericMethod方法只要求您指定generics类型参数,而不是方法的参数。

当您调用该方法时,您将在稍后传递参数。 然而,在这一点上,他们作为object传递,所以它再次无关紧要。