使用委托的Lambda函数

本文关键字:Lambda 函数 | 更新日期: 2023-09-27 17:57:26

我有以下内容:

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的情况下,可以重写以下内容以输出与上述内容相同的内容吗?

是否可以修改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();
    }
}

使用委托的Lambda函数

显然不能这样写。思考一下: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。

我想你正在练习使用delegates/lambdas,因为你本可以写这篇文章:

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