[英]How to call some method via Reflection without any parameters and any return values?
How to call some method via Reflection without any parameters and any return values? 如何通过反射调用一些没有任何参数和任何返回值的方法?
// Define a class with a generic method.
public class Example
{
public static void Generic<T>()
{
Console.WriteLine("\r\nHere it is: {0}", "DONE");
}
}
What should be within typeof(???) then? 那么typeof(???)内应该是什么?
MethodInfo miConstructed = mi.MakeGenericMethod(typeof(???));
Thank you!!! 谢谢!!!
Before being able to invoke a generic method you need to specify its generic argument(s). 在能够调用通用方法之前,您需要指定其通用参数。 So you pass the type you want to be used as generic argument:
因此,您传递要用作通用参数的类型:
public class Example
{
public static void Generic<T>()
{
Console.WriteLine("The type of T is: {0}", typeof(T));
}
}
class Program
{
static void Main()
{
var mi = typeof(Example).GetMethod("Generic");
MethodInfo miConstructed = mi.MakeGenericMethod(typeof(string));
miConstructed.Invoke(null, null);
}
}
which should print: 应该打印:
The type of T is: System.String
If you were invoking that through C#, you would need to supply a type, for example: 如果要通过C#调用它,则需要提供一个类型,例如:
Example.Generic<int>();
that requirement does not change; 该要求没有改变; simply, that line would become:
简单地,该行将变为:
mi.MakeGenericMethod(typeof(int)).Invoke(null, null);
For a complete, working illustration: 完整,有效的插图:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.