C# Lambda expressions: Why should I use them?

后端 未结 15 1628
栀梦
栀梦 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:21

    A lambda expression is like an anonymous method written in place of a delegate instance.

    delegate int MyDelagate (int i);
    MyDelagate delSquareFunction = x => x * x;
    

    Consider the lambda expression x => x * x;

    The input parameter value is x (on the left side of =>)

    The function logic is x * x (on the right side of =>)

    A lambda expression's code can be a statement block instead of an expression.

    x => {return x * x;};
    

    Example

    Note: Func is a predefined generic delegate.

        Console.WriteLine(MyMethod(x => "Hi " + x));
    
        public static string MyMethod(Func strategy)
        {
            return strategy("Lijo").ToString();
        }
    

    References

    1. How can a delegate & interface be used interchangeably?

提交回复
热议问题