C# switch in lambda expression

后端 未结 6 933
夕颜
夕颜 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条回答
  •  猫巷女王i
    2021-02-04 05:02

    Yes, it works, but you have to put your code in a block. Example:

    private bool DoSomething(Func callback)
    {
        return callback("FOO");
    }
    

    Then, to call it:

    DoSomething(val =>
                    {
                        switch (val)
                        {
                            case "Foo":
                                return true;
    
                            default:
                                return false;
                        }
                    });
    

提交回复
热议问题