【问题标题】:Lambda function using a delegate使用委托的 Lambda 函数
【发布时间】:2013-02-04 00:24:55
【问题描述】:

我有以下几点:

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();
    }
}

【问题讨论】:

  • 除非您正在练习使用委托,否则我不明白为什么在您的代码中需要使用委托。您拥有价值,并且知道如何处理它。
  • @AndersonSilva - 第一次就对了 - 我正在研究代表和 lambda 函数

标签: c# delegates lambda


【解决方案1】:

显然不能这样写。想一想:第二个代码中 x 的值是多少?您创建了委托的实例,但何时调用?

使用此代码:

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

【讨论】:

    【解决方案2】:

    你并不真的需要一个代表。 但是为了工作,你需要改变这一行:

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

    用这个:

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

    【讨论】:

    • +1 感谢 Petar - 但练习的重点是我试图了解代表以及 lambda 与它们的关系
    【解决方案3】:

    首先,您不需要委托。你可以直接相乘。但首先,代表的更正。

    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);
    

    【讨论】:

    • +1 完全正确 - 只是练习代表/lambda 并试图了解它们的工作原理
    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多