简体   繁体   中英

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? Can the following be re-written, without writeoutput , to output the same as the above?

Can the line Console.WriteLine("x^2 = {0}", new myDelegate(x => x*x)); be amended so that 3 is fed into the function?

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? 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. You can use a lambda directly.

I assume you're practicing the use of delegates/lambdas, because you could just have written this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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