【问题标题】:Code snippet. If in front of switch-statement代码片段。如果在 switch 语句前面
【发布时间】:2012-03-02 15:57:44
【问题描述】:

我有这样的代码:

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 变量呢?

【问题讨论】:

  • 您要重用还是减少 DoneFlag?我不太明白你的问题。
  • 我没有得到你的问题。最后一句应该是什么意思?
  • 如果您提出的问题对读者的要求很高,只是为了理解这个问题,如果没有人回答,请不要感到惊讶。
  • 没有 switch,没有 else if,你到底想做什么?
  • 好的,我必须回答(下)。如果你对多态性做一点研究,你就会得到答案。

标签: c# if-statement switch-statement


【解决方案1】:

您可以稍微优化您的解决方案,以便完成标志值将仅设置在单行中,所有其他将保持原样。你还好吗?

LINQAny():

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);

Enumerable.Any():

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

【讨论】:

    【解决方案2】:

    假设“减少”是指“消除”,则不使用 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
    }
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-10
        • 1970-01-01
        • 2022-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多