C# 将If/else If/else转换为C中的开关/Case

C# 将If/else If/else转换为C中的开关/Case,c#,if-statement,switch-statement,case,C#,If Statement,Switch Statement,Case,我正在完善我对数组和if/else if/else语句的理解。我想看看是否可以将if/else if/else语句转换为Switch/Case。最好的办法是什么?我听说,在处理范围更广的选择时,Switch/Case更有效。 我应该留在if/else吗?或者有没有办法将我的选择转换成开关盒? 下面是我在代码中为他们制作的示例 { int [] acct = new int [3]; acct[0] = 8675309; acct[1] = 86

我正在完善我对数组和if/else if/else语句的理解。我想看看是否可以将if/else if/else语句转换为Switch/Case。最好的办法是什么?我听说,在处理范围更广的选择时,Switch/Case更有效。 我应该留在if/else吗?或者有没有办法将我的选择转换成开关盒? 下面是我在代码中为他们制作的示例

{
        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");
        }
        */
    }
}
我是这样看的:

switchvalue声明了编码人员基于值做出分支决策的意图 if-else-if可以有任意条件 有一种偶然的可能性,而不是其他,如果在中间的链,可能导致错误或误解的原始编码器的意图。 直到C 6.0开关的情况是常量值,这意味着如果if-else-if链更灵活,您可能很难直接将其转换为C 6.0及以下版本的开关

从C7.0开始,引入了更灵活的模式,使得使用非常量模式成为可能


在C 8.0中,还有一些方法可以使代码在某些情况下更具可读性和简洁性。

您的问题是什么?不清楚你怎么能教别人一些你不知道的东西?但你知道开关/案例是常数吗?这就是为什么我要问的。我可以将if-else代码更改为switch-case语句吗?我正在尝试学习,以便展示执行相同基本代码的其他方法。如果使用switch将代码重构为switch,代码可能不会变得更清晰,但可以在a==acct[0]时执行switch myacct{case int a]:…等等。示例:-然而,您可能会从完全不同的方法中受益更多,但很难从简单的示例中分辨出来。