使用反射在对象实例上调用通用方法,并带有签名:someBobject.somegemegerIcInstancemethod (t参数)
-
12-10-2019 - |
题
我该怎么打电话 SomeObject.SomeGenericInstanceMethod<T>(T arg)
?
关于调用通用方法的文章有一些文章,但并不像这样。问题在于方法参数参数被限制为通用参数。
我知道签名是
SomeObject.SomeGenericInstanceMethod<T>(string arg)
那我可以得到MethodInfo
typeof (SomeObject).GetMethod("SomeGenericInstanceMethod", new Type[]{typeof (string)}).MakeGenericMethod(typeof(GenericParameter))
那么,当常规参数是通用类型时,如何获得MethodInfo?谢谢!
同样,对通用参数可能会构成或可能没有类型的约束。
解决方案
您以同样的方式进行操作。
当您致电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");
}
}
其他提示
您以完全相同的方式进行操作,但要传递对象的实例:
typeof (SomeObject).GetMethod(
"SomeGenericInstanceMethod",
yourObject.GetType())
// Or typeof(TheClass),
// or typeof(T) if you're in a generic method
.MakeGenericMethod(typeof(GenericParameter))
这 makegenericMethod 方法仅要求您指定通用类型参数,而不是方法的参数。
稍后,当您调用该方法时,您将通过参数。但是,在这一点上,他们通过了 object
, ,这再次无关紧要。
不隶属于 StackOverflow