代码段.如果在开关语句前面

本文关键字:语句 前面 开关 如果 代码 | 更新日期: 2023-09-27 18:26:32

我有这样的代码:

if (pref_const == Constants.PREF_PricingTypesFormWidth)
{
    a = 2;
    b = 3;   
    DoneFlag = true;
}
if (pref_const == Constants.PREF_PricingTypesFormTop)
{
    a = 4;
    b = 2; 
    DoneFlag = true;
}
......
if(!DoneFlag)//replacing of default-section in switch-statement
{
    //DoSthng
}

以及许多其他if语句。不要问我为什么不使用switch语句。那么,有什么方法可以减少DoneFlag变量吗??

代码段.如果在开关语句前面

您可以稍微优化您的解决方案,这样Done标志值将仅在一行中设置,其他所有值都将保持原样。这对您来说合适吗?

LINQ Any():

using System.Linq;
// Assuming constants are strings
IList<string> constants = new List<string> 
           {
              Constants.PREF_PricingTypesFormWidth,
              Constants.PREF_PricingTypesFormTop,
           };
bool DoneFlag = constants.Any(p => p == perf_const);

可枚举.Any():

确定序列的任何元素是否满足条件

假设"reduce"的意思是"exclude",那么不使用DoneFlag的嵌套if-then-else语句的逻辑等价链如下:

if (pref_const == Constants.PREF_PricingTypesFormWidth)
{
    a = 2;
    b = 3;   
}
else // <<===
if (pref_const == Constants.PREF_PricingTypesFormTop)
{
    a = 4;
    b = 2; 
}
else //replacing of default-section in switch-statement
{
    //DoSthng
}

使用多态性:让每个具体类设置变量,这样您的消费代码就不知道或不在乎是哪个类在做这件事。

注意:由于你的接受率,这个答案故意简短。