使用反射调用带有签名的对象实例上的泛型方法:SomeObject.SomeGenericInstanceMethod(T argument)
如何调用 SomeObject.SomeGenericInstanceMethod
?
有几篇关于调用泛型方法的文章,但不太像这篇文章。问题在于方法参数参数被限制为泛型参数。
我知道如果签名是
SomeObject.SomeGenericInstanceMethod
获取 MethodInfo
那么我可以使用typeof (SomeObject).GetMethod("SomeGenericInstanceMethod", new Type[] {typeof (string)}).MakeGenericMethod(typeof(GenericParameter))
那么,当常规参数是泛型类型时,如何获取 MethodInfo 呢?谢谢!
此外,通用参数可能有也可能没有类型约束。
How do I call SomeObject.SomeGenericInstanceMethod<T>(T arg)
?
There are a few posts about calling generic methods, but not quite like this one. The problem is that the method argument parameter is constrained to the generic parameter.
I know that if the signature were instead
SomeObject.SomeGenericInstanceMethod<T>(string arg)
then I could get the MethodInfo with
typeof (SomeObject).GetMethod("SomeGenericInstanceMethod", new Type[]{typeof (string)}).MakeGenericMethod(typeof(GenericParameter))
So, How do I go about getting the MethodInfo when the regular arguments are of a generic type? Thanks!
Also, there may or may not be type constrains on the generic parameter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你用完全相同的方式来做。
当您调用 MethodInfo.Invoke 时,您无论如何都会传递
object[]
中的所有参数,因此您不必在编译时知道类型。样本:
You do it exactly the same way.
When you call MethodInfo.Invoke, you pass all the arguments in an
object[]
anyway, so it's not like you have to know the types at compile time.Sample:
您以完全相同的方式执行此操作,但传递对象的实例:
MakeGenericMethod 方法只需要您指定泛型类型参数,而不是方法的参数。
当您稍后调用该方法时,您将传递参数。然而,此时,它们作为
对象
传递,所以这也没关系。You do it exactly the same way, but pass an instance of your object:
The MakeGenericMethod method only requires you to specify the generic type parameters, not the method's arguments.
You'd pass the arguments in later, when you call the method. However, at this point, they're passing as
object
, so it again doesn't matter.