题
这个问题是这个问题的补充 问题
在 C# 中,switch case 不能转换为其他 case,这会导致编译错误。在本例中,我只是将一些数字添加到所选月份及其后每个月的月份总数中。(简单的例子,并不意味着是真实的)
switch (month)
{
case 0:
add something to month totals
case 1:
add something to month totals
case 2:
add something to month totals
default:
break;
}
在 C# 中是否有一个逻辑替代方案,而无需编写大量 if 语句?
if (month <= 0)
add something to month
if (month <= 1)
add something to month
if (month <= 2)
add something to month
.... etc
解决方案
很多时候,当您看到来自一个巨大的 switch 语句或许多可能落入多个块的 if 语句的噪音时,您正在尝试抑制糟糕的设计。
相反,如果您实现规范模式来查看某些内容是否匹配,然后对其采取行动,该怎么办?
foreach(MonthSpecification spec in this.MonthSpecifications)
{
if(spec.IsSatisfiedBy(month))
spec.Perform(month);
}
然后你可以添加与你想要做的事情相匹配的不同规格。
很难说出你的域是什么,所以我的例子可能有点做作。
其他提示
在 C# switch 语句中,仅当没有针对您想要失败的情况的语句时,您才可以失败
switch(myVar)
{
case 1:
case 2: // Case 1 or 2 get here
break;
}
然而,如果你想通过一个语句,你必须使用可怕的 GOTO
switch(myVar)
{
case 1: // Case 1 statement
goto case 2;
case 2: // Case 1 or 2 get here
break;
}
您要添加常量吗?如果是这样,也许这样的东西会起作用(C 语法):
const int addToTotals[] = {123, 456, ..., 789};
for(i=month;i<12;i++)
totals += addToTotals[i];
如果您需要比将常量添加到随后每个月的总计中更复杂的语句,则可以使用变量或函数指针执行类似的操作。
-亚当
以相反的顺序写出 switch case
case 2:
case 1:
case 0:
break;
default:
希望有帮助!
不隶属于 StackOverflow