C# 代码片段。如果在switch语句前面

C# 代码片段。如果在switch语句前面,c#,if-statement,switch-statement,C#,If Statement,Switch Statement,我有这样的代码: 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 o

我有这样的代码:

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标志值将仅在单行中设置,其他所有标志值将保持不变。对你合适吗

林克:

使用System.Linq;
//假设常量是字符串
IList常量=新列表
{
Constants.PREF_PricingTypesFormWidth,
Constants.PREF_PricingTypesFormTop,
};
bool DoneFlag=constants.Any(p=>p==perf_const);
:

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

假设“reduce”的意思是“include”,则不使用
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
}
if(pref_const==Constants.pref_PricingTypesFormWidth)
{
a=2;
b=3;
}

else/使用多态性:让每个具体的类设置变量,这样您的消费代码就不知道或不关心是哪个类在执行它


注意:由于您的接受率,此答案故意简短。

您想重复使用还是减少
DoneFlag
?我不太明白你的问题,我没听清楚你的问题。最后一句话的意思是什么?如果你问了一个对读者要求很高的问题,只是为了理解这个问题,如果没有人回答,不要感到惊讶。没有开关,没有其他如果,你想做什么?好的,我必须回答(下面)。如果你对多态性做一点研究,你就会得到答案。
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
}