C# 如何在switch语句中合并两个带参数的案例
我想在C#中的switch语句中合并两个带有参数的案例 在字符、字符串和整数的情况下,合并大小写很容易:C# 如何在switch语句中合并两个带参数的案例,c#,switch-statement,C#,Switch Statement,我想在C#中的switch语句中合并两个带有参数的案例 在字符、字符串和整数的情况下,合并大小写很容易: switch (int) { case 1: case 2: { <do something> } } 我试着像这样把它们合并起来 case UpdateFeeCommand cmd: case CreateFeeCommand cmd: {} case UpdateFeeCommand: case CreateFeeComma
switch (int)
{
case 1:
case 2:
{
<do something>
}
}
我试着像这样把它们合并起来
case UpdateFeeCommand cmd:
case CreateFeeCommand cmd:
{}
case UpdateFeeCommand:
case CreateFeeCommand cmd:
{}
case UpdateFeeCommand, CreateFeeCommand cmd:
{}
等等,但这种语法不起作用。此外,我尝试将cmd
替换为value
,但是没有找到value.Fee
和value.Owner
,需要隐式转换为cmd
有可能合并这些情况吗?如果
UpdateFeeCommand
和CreateFeeCommand
是不相关的类型,它们恰好都具有相同名称的属性,那么您无法编写将它们视为同一类型的代码。您可以定义一个接口(或基类),该接口定义了这些公共属性,并让UpdateFreeCommand
和createfreecoment
实现该接口。然后您可以编写case IFreeCommand cmd
来处理这两个命令。在这种情况下,您通常会使用UpdateFeeCommand
和CreateFeeCommand
的基类或某个共享接口,可能是FeeCommand
或类似的东西,并将其用作案例。但是,这种方法的“缺点”是,每个FeeCommand
(即使是你不想用这种方式处理的命令)都会像这样处理,除非你在基本情况之前插入特定情况并将其打破。而且,这看起来有点奇怪,您正在使用updatefee命令的Fee
执行ApplyCreate
。仅从命名判断,您可能想要ApplyUpdate
no?您没有显示{}
部分,但这是最重要的部分。可以说,为不同类型使用相同的代码比较困难。您只需要将公共部分(如果它足够大)重构为一个方法(本地函数是nut)并从两个不同的case
s调用它?
case UpdateFeeCommand cmd:
case CreateFeeCommand cmd:
{}
case UpdateFeeCommand:
case CreateFeeCommand cmd:
{}
case UpdateFeeCommand, CreateFeeCommand cmd:
{}