根据条件反转if-else的最佳方法

时间:2015-11-27 19:56:21

标签: c# if-statement

我想要一个if-else子句基于一个输出来保持语句不变,或者在if和else之间切换语句。

具体来说,我正在解析html标记countryuncountry。根据其列出标签国家/地区的属性,我将能够决定是否跳过内部内容。 country标记将复制内部内容,而uncountry则相反。 if (parseCountry)用于解析country代码,而uncountry代码用于分析。

例如:

                if (parseCountry)
                {
                    if (inCountryList)
                    {
                        do A;
                        do B;
                    }
                    else if (notInCountryList)
                        do C;
                }
                else
                {
                    if (inCountryList)
                        do C;
                    else if (notInCountryList)
                    {
                        do A;
                        do B;
                    }
                }

简化上述if-else语句的最佳方法是什么?感谢。

2 个答案:

答案 0 :(得分:1)

我想这就是你要找的东西:

if (parseCountry == inCountryList)
{
    do A;
    do B;
}
else
{
    do C;
}

当两个布尔值具有相同值时,条件得以实现:两者都是True或两者都是False

答案 1 :(得分:1)

为方便起见,我将使用do AB;来反映您的双语句块。

总结您要实现的逻辑:如果parseCountryinCountryList两者具有相同的值,请执行do AB;,否则执行do C;,但要提供在任何一种情况下,仅当!inCountryList本身notInCountryList时才应执行true个案。

用C#( - ish)代码编写,看起来像这样:

if (inCountryList || notInCountryList)
{
    if (parseCountry == inCountryList)
    {
        do A;
        do B;
    }
    else
    {
        do C;
    }
}

或换句话说:如果inCountryListnotInCountryList都不是真的,则什么也不做。否则,根据parseCountry是否等于inCountryList来执行代码。这与您在问题中显示的实施情况一致。