C# switch in lambda expression

后端 未结 6 978
夕颜
夕颜 2021-02-04 04:04

Is it possible to have a switch in a lambda expression? If not, why? Resharper displays it as an error.

6条回答
  •  执笔经年
    2021-02-04 04:43

    I checked it too :-)

    [Test]
    public void SwitchInLambda()
    {
        TakeALambda(i => {
            switch (i)
            {
                case 2:
                    return "Smurf";
                default:
                    return "Gnurf";
            }
        });
    }
    
    public void TakeALambda(Func func)
    {
        System.Diagnostics.Debug.WriteLine(func(2));
    }
    

    Works just fine (outputs "Smurf")!

提交回复
热议问题