c# - switch 表达式中的多个语句:C# 8
问题描述
Switch 表达式是在 C# 8 中引入的。代码库中有很多地方可以用这种新风格重写。
例如,我有一些代码,用于从字节流中解析数据包:
switch (command)
{
case Command.C1:
return new P1();
case Command.C2:
return new P2();
default:
stream.Position++;
return null;
}
问题是 - 它不能转换为 switch 表达式
return command switch
{
Command.C1 => new P1(),
Command.C3 => new P2(),
_ => { stream.Position++; return null; }
};
我想到的第一件事是使用 a 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 表达式而没有任何奇怪的黑客攻击?
解决方案
您唯一受支持的选择是您所做的 func 。有关更多信息,请参阅本文。他的例子:
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 表达式是新的并不意味着它们是所有用例的最佳选择。它们并非旨在包含多个命令。
推荐阅读
- r - 如何在R中找到公共变量对?
- python - Python-从数据框中选择对象对
- reactjs - React、Typescript 和 setState({ [name]: value }) 错误
- amazon-web-services - 在 Lambda 函数中查找请求的 URL
- sql - 语句中带有运算符的条件 WHERE 子句
- android - 仅为“群组”打开通知设置
- intellij-idea - 在演示模式下显示编辑器选项卡
- javascript - Javascript Div 类默认选项卡
- java - 将构造函数中的 System.getProperty 替换为 yml
- ios - 如何捆绑名称与捆绑显示名称与 AppStoreConnect 应用程序名称