Switch/Case 和 If - 我的案例有更好的解决方案吗?

问题描述 投票:0回答:1

目前我需要根据从计算机名称、位置和扇区获取的 2 个变量来自动化安装和配置。每个位置的每个扇区都有彼此完全不同的配置。

有没有比在每个位置的“switch/case”中对每个扇区使用“if”更好的方法? (每个位置的扇区数小于位置数)

谢谢!

示例:

public void install(string l, string s)
{
    
    switch (l)
    {
        case "10":
            {
                if (s == "CS" || s == "BO")
                {
                    //do stuff1
                    //do stuff2
                }
                if (s == "RR")
                {
                    //do stuff1
                    //do stuff2
                }
                if (s == "RC")
                {
                    //do stuff1
                    //do stuff2
                }
                break;
            }

        case "20":
            {
                if (s == "CS" || s == "BO")
                {
                    //do stuff1
                    //do stuff2
                }
                if (s == "RE")
                {
                    //do stuff1
                    //do stuff2
                    //do stuff3
                }
                if (s == "RC")
                {
                    //do stuff1
                    //do stuff2
                }
                break;
            }

        case "21":
            {
                if (s == "CS" || s == "BO")
                {
                    //do stuff1
                    
                }
                if (s == "RE")
                {
                    //do stuff1
                    //do stuff2
                }
                if (s == "RX")
                {
                    //do stuff1
                    //do stuff2
                }
                break;
            }
        (...)
    }
}

使用 Switch/Case,如果它太大并且有点凌乱,我不知道是否有更好的方法,我忘记了。

c# if-statement switch-statement
1个回答
0
投票

您可以使用

else if

 public void install(string l, string s)
        {

            switch (l)
            {
                case "10":
                    {
                        if (s == "CS" || s == "BO")
                        {
                            // executed only if "condition" is true                                
                        }
                        else if (s == "RR")
                        {
                             // executed only if "condition" was false and "other condition" is true                               
                        }
                        else 
                        {
                            // executed only if both "condition" and "other condition" were false
                        }
                        break;
                    }
            }
        }

答案参考:if、else、else if有什么区别?

© www.soinside.com 2019 - 2024. All rights reserved.