使用反射来调用对象实例泛型方法有签名:SomeObject.SomeGenericInstanceMethod< T>(T参数) [英] Use Reflection to call generic method on object instance with signature: SomeObject.SomeGenericInstanceMethod<T>(T argument)
问题描述
我怎么叫 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> (字符串ARG)
然后我可以用
的typeof(SomeObject).GetMethod(SomeGenericInstanceMethod,新类型[] {typeof运算(字符串)})。MakeGenericMethod(typeof运算(的GenericParameter))
所以,我怎么去获得的MethodInfo当定时参数是泛型类型的?谢谢!
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.
推荐答案
您这样做完全一样的方式。
You do it exactly the same way.
当你调用MethodInfo.Invoke,你传递一个对象中的所有参数[ ]
无论如何,所以它不是像你必须知道的类型在编译时
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.
示例:
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");
}
}
这篇关于使用反射来调用对象实例泛型方法有签名:SomeObject.SomeGenericInstanceMethod< T>(T参数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!