Multiple statements in a switch expression: C# 8

橙三吉。 提交于 2020-12-08 06:53:11

问题


Switch expressions were introduced in C# 8. There's plenty of places in codebases, which may be rewritten in this new style.

For example, I have some code, which is used for parsing packets from a stream of bytes:

switch (command)
{
    case Command.C1:
        return new P1();
    case Command.C2:
        return new P2();
    default:
        stream.Position++;
        return null;
}

The problem is - it can't be converted to a switch expression like

return command switch
{
    Command.C1 => new P1(),
    Command.C3 => new P2(),
    _ => { stream.Position++; return null; }
};

The first thing that got in my mind was to use a Func<>, which compiles:

return command switch
{
    Command.C1 => new P1(),
    Command.C3 => new P2(),
    _ => new Func<AbstractPacket>(() => { stream.Position++; return null; })()
};

F# already allows code with multiple statements in each branch:

match command with
| Command.C1 -> Some(P1() :> AbstractPacket)
| Command.C2 -> Some(P2() :> AbstractPacket)
| _ ->
    stream.Position <- stream.Position + 1
    None

Now I'm stuck using switch-statements, but is there any option to write this as a switch-expression without any weird hacks?


回答1:


Your only supported choice is the func like you did. See this article for more information. His example:

var result = operation switch
{
"+" => ((Func<int>)(() => {
    Log("addition");
    return a + b;
}))(),
"-" => ((Func<int>)(() => {
    Log("subtraction");
    return a - b;
}))(),
"/" => ((Func<int>)(() => {
    Log("division");
    return a / b;
}))(),
_ => throw new NotSupportedException()
};

Just because switch expressions are new doesn't mean they are the best for all use cases. They are not designed to contain multiple commands.




回答2:


With:

TRes Call<TRes>(Func<TRes> f) => f();

its looks like:

return command switch {
  Command.C1 => new P1(),
  Command.C3 => new P2(),
  _ => Call(() => { stream.Position++; return null; }),
};

or:

var result = operation switch {
  "+" => Call(() => {
    Log("addition");
    return a + b;
  }),
  "-" => Call(() => {
    Log("subtraction");
    return a - b;
  }),
  "/" => Call(() => {
    Log("division");
    return a / b;
  }),
  _ => throw new NotSupportedException(),
};


来源:https://stackoverflow.com/questions/59890226/multiple-statements-in-a-switch-expression-c-sharp-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!