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

后端 未结 17 1416
小蘑菇
小蘑菇 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:59

    A delegate is a Queue of function pointers, invoking a delegate may invoke multiple methods. A lambda is essentially an anonymous method declaration which may be interpreted by the compiler differently, depending on what context it is used as.

    You can get a delegate that points to the lambda expression as a method by casting it into a delegate, or if passing it in as a parameter to a method that expects a specific delegate type the compiler will cast it for you. Using it inside of a LINQ statement, the lambda will be translated by the compiler into an expression tree instead of simply a delegate.

    The difference really is that a lambda is a terse way to define a method inside of another expression, while a delegate is an actual object type.

提交回复
热议问题