如何使用反射调用泛型方法?

£可爱£侵袭症+ 提交于 2020-08-12 04:58:59

问题:

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? 当类型参数在编译时未知,而是在运行时动态获取时,调用通用方法的最佳方法是什么?

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? 考虑以下示例代码-在Example()方法内部,使用存储在myType变量中的Type调用GenericMethod<T>()的最简洁方法是什么?

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>()
    {
        //...
    }
}

解决方案:

参考一: https://stackoom.com/question/yUZ/如何使用反射调用泛型方法
参考二: https://oldbug.net/q/yUZ/How-do-I-use-reflection-to-call-a-generic-method
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!