首页 > 解决方案 > 如何在 switch 语句中将两个案例与参数合并

问题描述

我想在 C# 的 switch 语句中将两个案例与参数合并。

在字符、字符串和整数的情况下,很容易合并案例:

switch (int)
{
    case 1:
    case 2:
    {
        <do something>
    }
}

并且可以找到很多关于此的信息(例如,如何在一个 switch 语句中合并两个 case 语句),但这不适用于更复杂的情况,例如ICommands。

问题+我尝试过的

我的代码如下所示:

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:
{}

等等,但这种语法不起作用。此外,我尝试过替换cmdvalue,但随后value.Feevalue.Owner没有找到并且需要隐式转换为cmd.

是否可以合并这些案例?

标签: c#switch-statement

解决方案


推荐阅读