Switch表达式是在C# 8中引入的。代码库中有很多地方,可以用这种新风格重写。
例如,我有一些代码,用于解析字节流中的数据包:
switch (command)
{
case Command.C1:
return new P1();
case Command.C2:
return new P2();
default:
stream.Position++;
return null;
}问题是-它不能被转换成开关表达式,比如
return command switch
{
Command.C1 => new P1(),
Command.C3 => new P2(),
_ => { stream.Position++; return null; }
};我想到的第一件事就是使用Func<>,它编译如下:
return command switch
{
Command.C1 => new P1(),
Command.C3 => new P2(),
_ => new Func<AbstractPacket>(() => { stream.Position++; return null; })()
};F#已经允许在每个分支中使用多个语句的代码:
match command with
| Command.C1 -> Some(P1() :> AbstractPacket)
| Command.C2 -> Some(P2() :> AbstractPacket)
| _ ->
stream.Position <- stream.Position + 1
None现在我不得不使用switch语句,但是有没有什么办法可以把它写成一个switch-expression而不会有任何奇怪的问题呢?
发布于 2020-01-24 12:42:28
你唯一支持的选择就是和你一样的func。有关详细信息,请参阅this article。他的例子是:
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()
};仅仅因为switch表达式是新的并不意味着它们在所有用例中都是最好的。它们不是设计为包含多个命令的。
发布于 2020-09-18 05:36:51
通过以下方式:
TRes Call<TRes>(Func<TRes> f) => f();它看起来像这样:
return command switch {
Command.C1 => new P1(),
Command.C3 => new P2(),
_ => Call(() => { stream.Position++; return null; }),
};或者:
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
复制相似问题