[英]Pass Method ( of void return type and with no input arguments) as parameter using C#
我想使用C#將方法(返回類型為void且沒有輸入參數)作為參數傳遞。 以下是我的示例代碼。 我該怎么做 ?
public void Method1()
{
... do something
}
public int Method2()
{
... do something
}
public void RunTheMethod([Method Name passed in here] myMethodName)
{
myMethodName();
... do more stuff
}
System.Action符合要求:
http://msdn.microsoft.com/en-us/library/system.action.aspx
對於具有參數但返回類型為void的方法,您還可以獲得Action的各種通用版本,對於返回某些內容的方法,您可以使用Func。
所以您的RunTheMethod方法看起來像
public void RunTheMethod(Action myMethod)
{
myMethod();
}
然后,您可以使用以下命令調用它:
RunTheMethod(Method1);
RunTheMethod(Method2);
如前所述,您可以使用委托-在您的情況下,可以使用System.Action
來做到這一點。
public void RunTheMethod(System.Action myMethodName)
{
myMethodName();
... do more stuff
}
//Delegate
public delegate void OnDoStuff();
class Program
{
static void Main(string[] args)
{
//Pass any of the method name here
Invoker(Method1);
Console.ReadLine();
}
private static void Invoker(OnDoStuff method)
{
method.Invoke();
}
private static void Method1()
{
Console.WriteLine("Method1 from method " + i);
}
private static void Method2()
{
Console.WriteLine("Method2 from method " + i);
}
private static void Method3()
{
Console.WriteLine("Method3 from method " + i);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.