问题:
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
来源:oschina
链接:https://my.oschina.net/stackoom/blog/4314994