c# - 如何在 switch 语句中将两个案例与参数合并
问题描述
我想在 C# 的 switch 语句中将两个案例与参数合并。
在字符、字符串和整数的情况下,很容易合并案例:
switch (int)
{
case 1:
case 2:
{
<do something>
}
}
并且可以找到很多关于此的信息(例如,如何在一个 switch 语句中合并两个 case 语句),但这不适用于更复杂的情况,例如ICommand
s。
问题+我尝试过的
我的代码如下所示:
public override Task<IEnumerable<IEvent>> Handle(ICommand value, CancellationToken cancellationToken)
{
switch (value)
{
case UpdateFeeCommand cmd:
{
ApplyCreate(cmd.Fee, cmd.Owner);
break;
}
case CreateFeeCommand cmd:
{
<identical implementation>
}
(...)
}
}
我试图像这样合并它们
case UpdateFeeCommand cmd:
case CreateFeeCommand cmd:
{}
case UpdateFeeCommand:
case CreateFeeCommand cmd:
{}
case UpdateFeeCommand, CreateFeeCommand cmd:
{}
等等,但这种语法不起作用。此外,我尝试过替换cmd
为value
,但随后value.Fee
并value.Owner
没有找到并且需要隐式转换为cmd
.
是否可以合并这些案例?
解决方案
推荐阅读
- amazon-web-services - AWS 数据管道中是否存在任何 aws datapipeline list-runs 等效 API?
- python - 如何按命名值对 Python 字典进行排序
- powerbi - 将动态列名连接到表 - Power Query
- git - 如何在 Eclipse 中将分支从远程拉到本地(更新分支)
- r - 为不在包中的 R6 类创建 Rd 文档文件
- node.js - 如何在 Nodejs 中使用 gmail api 在同一对话中回复电子邮件
- google-cloud-platform - 无法将 Cloud SQL 移动到不同的子网或 vpc
- html - 导航栏标题有问题,如何解决?
- flutter - 未处理的异常:类型“FlutterError”不是类型转换中“异常”类型的子类型
- swift - SwiftUI 使用 @FetchRequest 绑定相关实体不会更新视图