C# switch in lambda expression

后端 未结 6 923
夕颜
夕颜 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:40

    You can in a statement block lambda:

    Action action = x =>
    {
      switch(x)
      {
        case 0: Console.WriteLine("0"); break;
        default: Console.WriteLine("Not 0"); break;
      }
    };
    

    But you can't do it in a "single expression lambda", so this is invalid:

    // This won't work
    Expression> action = x =>
      switch(x)
      {
        case 0: return 0;
        default: return x + 1;
      };
    

    This means you can't use switch in an expression tree (at least as generated by the C# compiler; I believe .NET 4.0 at least has support for it in the libraries).

提交回复
热议问题