在C#中将If / else if / else转换为Switch / Case

时间:2019-10-01 11:45:49

标签: c# if-statement switch-statement case

我正在完善对数组以及if / else if / else语句的理解。我想看看是否可以将if / else if / else语句转换为Switch / Case。最好的方法是什么?我听说Switch / Case在处理更多选择时效率更高。 我应该留在if / else吗?还是有办法将我的选择转换成Switch Case? 这是我为他们和代码中的示例。

{
        int []  acct = new int [3];

        acct[0] = 8675309;
        acct[1] = 8675310;
        acct[2] = 8675311;

        Console.WriteLine("Enter your account number");
        int myacct = int.Parse(Console.ReadLine());
        //int myacct = Convert.ToInt32(Console.ReadLine());<--This works too
        if (myacct == acct[0])
        {
            Console.WriteLine("What is your name?");
        }
        else if (myacct == acct[1])
        {
            Console.WriteLine("What is your name?");
        }
        else if (myacct == acct[2])
        {
            Console.WriteLine("What is your name?");
        }
        else
        {
            Console.WriteLine("Sorry you don't have access");
        }

        string name = Console.ReadLine();

        string[] names = new string[3] { "Jenny", "Roberto", "Sally" };
        /*  This shows them how to tighten the code up compaired to the technique we used above
        names[0] = "Jenny";
        names[1] = "Roberto";
        names[2] = "Sally";
        */

        //I'd like to make the following code into a Switch and Case type statement instead of using else if.


        /*
        if (myacct == acct [0] && name == "Jenny")
        {
            Console.WriteLine("Welcome "+names[0] + "!");
        }


        else if (myacct == acct[1] && name == "Roberto")
        {
            Console.WriteLine("Welcome Roberto" + names[1] + "!");
        }
        else if (myacct == acct[2] && name == "Sally")
        {
            Console.WriteLine("Welcome Sally" + names[2] + "!");
        }
        else
        {
            Console.WriteLine("Account number and Names do not match");
        }
        */
    }
}

1 个答案:

答案 0 :(得分:0)

我这样看:

  • switch(value)声明编码者打算根据value做出分支决策
  • if-else if可以具有任意条件
  • 在链的中间存在偶然的if而不是else if的可能性,这可能导致错误或对原始编码者意图的误解。

具有恒定值的C#6.0 switch的{​​{1}} could only operate,这意味着case-if链可以更灵活在C#6.0及更低版本中,可能很难将其直接转换为else if

从C#7.0开始,引入了更加灵活的pattern matching,从而可以使用非恒定模式。

在C#8.0中,还有switch expressionsproperty and tuple patterns在某些情况下可以使代码更具可读性和简洁性。