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

后端 未结 17 1414
小蘑菇
小蘑菇 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 11:15

    Lambdas are simplified versions of delegates. They have some of the the properties of a closure like anonymous delegates, but also allow you to use implied typing. A lambda like this:

    something.Sort((x, y) => return x.CompareTo(y));
    

    is a lot more concise than what you can do with a delegate:

    something.Sort(sortMethod);
    ...
    
    private int sortMethod(SomeType one, SomeType two)
    {
        one.CompareTo(two)
    }
    

提交回复
热议问题