2

我怎么打电话SomeObject.SomeGenericInstanceMethod<T>(T arg)

有一些关于调用泛型方法的帖子,但不太像这个。问题是方法参数参数被限制为泛型参数。

我知道如果签名是

SomeObject.SomeGenericInstanceMethod<T>(string arg)

然后我可以得到 MethodInfo

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

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

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

4

2 回答 2

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");
    }
}
于 2011-01-19T17:07:11.963 回答
2

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

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

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.

于 2011-01-19T17:07:25.490 回答