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

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

    One difference is that an anonymous delegate can omit parameters while a lambda must match the exact signature. Given:

    public delegate string TestDelegate(int i);
    
    public void Test(TestDelegate d)
    {}
    

    you can call it in the following four ways (note that the second line has an anonymous delegate that does not have any parameters):

    Test(delegate(int i) { return String.Empty; });
    Test(delegate { return String.Empty; });
    Test(i => String.Empty);
    Test(D);
    
    private string D(int i)
    {
        return String.Empty;
    }
    

    You cannot pass in a lambda expression that has no parameters or a method that has no parameters. These are not allowed:

    Test(() => String.Empty); //Not allowed, lambda must match signature
    Test(D2); //Not allowed, method must match signature
    
    private string D2()
    {
        return String.Empty;
    }
    

提交回复
热议问题