如何在没有参数和返回值的情况下通过反射调用某个方法?
这是 MSDN sample
// Define a class with a generic method.
public class Example
{
public static void Generic<T>()
{
Console.WriteLine("\r\nHere it is: {0}", "DONE");
}
}
那么 typeof(???) 中应该包含什么?
MethodInfo miConstructed = mi.MakeGenericMethod(typeof(???));
谢谢!!!
最佳答案
如果您通过 C# 调用它,则需要提供一个类型,例如:
Example.Generic<int>();
该要求不会改变;简单地说,那一行会变成:
mi.MakeGenericMethod(typeof(int)).Invoke(null, null);
要获得完整的工作图:
class Example
{
public static void Generic<T>()
{
System.Console.WriteLine("\r\nHere it is: {0}", "DONE");
}
static void Main()
{
var mi = typeof (Example).GetMethod("Generic");
mi.MakeGenericMethod(typeof(int)).Invoke(null, null);
}
}
关于c# - 如何在没有任何参数和任何返回值的情况下通过反射调用某些方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8416534/