C# Lambda expressions: Why should I use them?

后端 未结 15 1511
栀梦
栀梦 2020-11-22 03:51

I have quickly read over the Microsoft Lambda Expression documentation.

This kind of example has helped me to understand better, though:

delegate in         


        
15条回答
  •  独厮守ぢ
    2020-11-22 04:01

    You can also find the use of lambda expressions in writing generic codes to act on your methods.

    For example: Generic function to calculate the time taken by a method call. (i.e. Action in here)

    public static long Measure(Action action)
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        action();
        sw.Stop();
        return sw.ElapsedMilliseconds;
    }
    

    And you can call the above method using the lambda expression as follows,

    var timeTaken = Measure(() => yourMethod(param));
    

    Expression allows you to get return value from your method and out param as well

    var timeTaken = Measure(() => returnValue = yourMethod(param, out outParam));
    

提交回复
热议问题