如何致电SomeObject.SomeGenericInstanceMethod<T>(T arg)
?
有一些关于调用泛型方法的帖子,但不完全像这个。问题是method参数被约束为泛型参数。
我知道如果签名是
SomeObject.SomeGenericInstanceMethod<T>(string arg)
然后我可以用
获取MethodInfo typeof (SomeObject).GetMethod("SomeGenericInstanceMethod", new Type[]{typeof (string)}).MakeGenericMethod(typeof(GenericParameter))
那么,当常规参数是泛型类型时,如何获取MethodInfo?谢谢!
此外,泛型参数可能有也可能没有类型约束。
答案 0 :(得分:11)
你的方式完全一样。
当您调用MethodInfo.Invoke时,无论如何都会传递object[]
中的所有参数,因此您不必在编译时知道类型。
样品:
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'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");
}
}
答案 1 :(得分:2)
您以完全相同的方式执行此操作,但传递对象的实例:
typeof (SomeObject).GetMethod(
"SomeGenericInstanceMethod",
yourObject.GetType())
// Or typeof(TheClass),
// or typeof(T) if you're in a generic method
.MakeGenericMethod(typeof(GenericParameter))
MakeGenericMethod方法只要求您指定泛型类型参数,而不是方法的参数。
当你调用方法时,你将在稍后传递参数。但是,此时,它们的传递时间为object
,因此无关紧要。