What is the difference between lambdas and delegates in the .NET Framework?

后端 未结 17 1344
小蘑菇
小蘑菇 2020-12-12 10:45

I get asked this question a lot and I thought I\'d solicit some input on how to best describe the difference.

17条回答
  •  抹茶落季
    2020-12-12 10:50

    A delegate is a function signature; something like

    delegate string MyDelegate(int param1);
    

    The delegate does not implement a body.

    The lambda is a function call that matches the signature of the delegate. For the above delegate, you might use any of;

    (int i) => i.ToString();
    (int i) => "ignored i";
    (int i) => "Step " + i.ToString() + " of 10";
    

    The Delegate type is badly named, though; creating an object of type Delegate actually creates a variable which can hold functions -- be they lambdas, static methods, or class methods.

提交回复
热议问题