简体   繁体   English

使用委托的Lambda函数

[英]Lambda function using a delegate

I have the following: 我有以下几点:

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

Is the method writeOutput in the above required? 上面的方法writeOutput是否必需? Can the following be re-written, without writeoutput , to output the same as the above? 可以在没有writeoutput情况下writeoutput以下内容以输出与上述相同的内容吗?

Can the line Console.WriteLine("x^2 = {0}", new myDelegate(x => x*x)); Console.WriteLine("x^2 = {0}", new myDelegate(x => x*x)); be amended so that 3 is fed into the function? 修改以便将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();
    }
}

It obviously can't be written that way. 显然不能这样写。 Think about this: what value x has in the second code? 考虑一下:第二个代码中x的值是多少? you create an instance of your delegate, but when it is called? 您创建委托的实例,但是何时调用它?

Use this code: 使用此代码:

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

You fon't really need a delagate. 您真的不需要脱盐。 But in order to work you need to change this line: 但是为了工作,您需要更改此行:

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

with this: 有了这个:

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

Firstly, you don't need a delegate. 首先,您不需要代表。 You can just multiply it directly. 您可以直接将其相乘。 But first, the correction of the delegate. 但是首先,代表的更正。

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

You should treat every instance of a delegate like a function, in the same way you do it in the first example. 您应该像在第一个示例中一样将委托的每个实例都视为函数。 The new myDelegate(/* blah blah */) is not necessary. new myDelegate(/* blah blah */) You can use a lambda directly. 您可以直接使用lambda。

I assume you're practicing the use of delegates/lambdas, because you could just have written this: 我假设您正在练习使用委托/ lambda,因为您可以编写以下代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM