使用Reflection通过签名调用对象实例上的泛型方法:SomeObject.SomeGenericInstanceMethod <T>(T参数)

sma*_*man 2 c# generics reflection methodinfo generic-method

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

有一些关于调用泛型方法的帖子,但不完全像这个.问题是method参数被约束为泛型参数.

我知道如果签名是相反的

SomeObject.SomeGenericInstanceMethod<T>(string arg)

然后我可以得到MethodInfo

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

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

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

Jon*_*eet 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");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果名为"name"的方法有多个重载,这仍然可以工作吗? (2认同)

归档时间:

查看次数:

13253 次

最近记录:

14 年,7 月 前