簡體   English   中英

使用委托的Lambda函數

[英]Lambda function using a delegate

我有以下幾點:

class Program {

    delegate int myDelegate(int x);

    static void Main(string[] args) {

        Program p = new Program();
        Console.WriteLine(p.writeOutput(3, new myDelegate(x => x*x)));

        Console.WriteLine("press [enter] to exit");
        Console.ReadLine();
    }
    private string writeOutput(int x, myDelegate del) {
        return string.Format("{0}^2 = {1}",x, del(x));
    }
}

上面的方法writeOutput是否必需? 可以在沒有writeoutput情況下writeoutput以下內容以輸出與上述相同的內容嗎?

Console.WriteLine("x^2 = {0}", new myDelegate(x => x*x)); 修改以便將3饋入函數?

class Program {

    delegate int myDelegate(int x);

    static void Main(string[] args) {

        Program p = new Program();

        Console.WriteLine("x^2 = {0}", new myDelegate(x => x*x));

        Console.WriteLine("press [enter] to exit");
        Console.ReadLine();
    }
}

顯然不能這樣寫。 考慮一下:第二個代碼中x的值是多少? 您創建委托的實例,但是何時調用它?

使用此代碼:

myDelegate myDelegateInstance = new myDelegate(x => x * x);
Console.WriteLine("x^2 = {0}", myDelegateInstance(3));

您真的不需要脫鹽。 但是為了工作,您需要更改此行:

    Console.WriteLine("x^2 = {0}", new myDelegate(x => x*x));

有了這個:

    Console.WriteLine("{0}^2 = {1}", x, x*x);

首先,您不需要代表。 您可以直接將其相乘。 但是首先,代表的更正。

myDelegate instance = x => x * x;
Console.WriteLine("x^2 = {0}", instance(3));

您應該像在第一個示例中一樣將委托的每個實例都視為函數。 new myDelegate(/* blah blah */) 您可以直接使用lambda。

我假設您正在練習使用委托/ lambda,因為您可以編寫以下代碼:

Console.WriteLine("x^2 = {0}", 3 * 3);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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