簡體   English   中英

使用C#的Pass方法(無效返回類型且沒有輸入參數)作為參數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM