![](/img/trans.png)
[英]How to implement a callback that could receive any parameters and return any values?
[英]How to call some method via Reflection without any parameters and any return values?
如何通過反射調用一些沒有任何參數和任何返回值的方法?
這是MSDN 示例
// 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(???));
謝謝!!!
在能夠調用通用方法之前,您需要指定其通用參數。 因此,您傳遞要用作通用參數的類型:
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);
}
}
應該打印:
The type of T is: System.String
如果要通過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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.