如何使用反射来调用泛型方法? [英] How do I use reflection to call a generic method?

查看:25
本文介绍了如何使用反射来调用泛型方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当类型参数在编译时未知,而是在运行时动态获取时,调用泛型方法的最佳方法是什么?

What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime?

考虑以下示例代码 - 在 Example() 方法中,使用 Type<调用 GenericMethod() 的最简洁方法是什么?/code> 存储在 myType 变量中吗?

Consider the following sample code - inside the Example() method, what's the most concise way to invoke GenericMethod<T>() using the Type stored in the myType variable?

public class Sample
{
    public void Example(string typeName)
    {
        Type myType = FindType(typeName);

        // What goes here to call GenericMethod<T>()?
        GenericMethod<myType>(); // This doesn't work

        // What changes to call StaticMethod<T>()?
        Sample.StaticMethod<myType>(); // This also doesn't work
    }

    public void GenericMethod<T>()
    {
        // ...
    }

    public static void StaticMethod<T>()
    {
        //...
    }
}

推荐答案

您需要使用反射来获取方法的开始,然后通过提供带有 MakeGenericMethod:

You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with MakeGenericMethod:

MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);

对于静态方法,将 null 作为第一个参数传递给 Invoke.这与泛型方法无关——它只是普通的反射.

For a static method, pass null as the first argument to Invoke. That's nothing to do with generic methods - it's just normal reflection.

如前所述,使用 dynamic 的 C# 4 中的很多都更简单 - 当然,如果您可以使用类型推断.在类型推断不可用的情况下,它没有帮助,例如问题中的确切示例.

As noted, a lot of this is simpler as of C# 4 using dynamic - if you can use type inference, of course. It doesn't help in cases where type inference isn't available, such as the exact example in the question.

这篇关于如何使用反射来调用泛型方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆