C#中如何转移goto语句的控制权

vik*_*mnr 3 c# loops goto control-structure

我是编程初学者,我正在尝试这个简单的程序来获取用户名并对其进行排序等等。

class Program
{
    static void Main(string[] args)
    {
        int number;
        dynamic y;

        string[] answer = new string[10];
        cases:
        Console.WriteLine("Enter the options given below 1.Add students\n 2.View all details\n 3.Sorting\n 4.Exit\n");
        int input = Convert.ToInt16(Console.ReadLine());
        switch (input)
        {
            case 1:
                Console.WriteLine("Enter the Number of Students to be added to the List");
                number = Convert.ToInt16(Console.ReadLine());
                for (int i = 0; i < number; i++)
                {
                    answer[i] = Console.ReadLine();
                }
            case 2:
                foreach (var item in answer)
                {
                    Console.WriteLine(item.ToString());
                }
                break;
            case 3:
                Array.Sort(answer);
                foreach (var item in answer)
                {
                    Console.WriteLine(item.ToString());
                }
                break;
            case 4:
                Console.WriteLine("Are you sure you want to exit");
                Console.WriteLine("1 for Yes and N for No");
                y = (char)Console.Read();
                if ((y == 1))
                {
                    goto cases;
                }
                else
                {
                    goto thankyou;
                }
                thankyou:
                Console.WriteLine("thank you");
                break;
        }
        Console.WriteLine("Are you sure you want to exit");
        Console.WriteLine("Y for Yes and 1 for No");
        y = (char)Console.Read();
        if ((y == 1))
        {
            goto cases;
        }
        else
        {
            goto thankyou;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是每次操作后我都会问它是否应该继续。我添加了go-to语句,但是当按下 No 时,它显示了input我声明的变量的异常。

我可以使用该go-to方法还是有什么方法可以做到这一点? 这是我得到的例外 任何建议这里有什么问题?

shf*_*301 5

如果您想在程序中使用循环,则应使用 C# 中的循环结构之一。在这种情况下,while循环将起作用:

bool keepPrompting = true;
while(keepPrompting) {
     Console.WriteLine("Enter the options given below 1.Add students\n 2.View all details\n 3.Sorting\n 4.Exit\n");
    int input = Convert.ToInt16(Console.ReadLine());

    // The case statement on input goes here

     Console.WriteLine("Are you sure you want to exit");
     Console.WriteLine("Y for Yes and 1 for No");
     var y = (char)Console.Read();
     if (y != 'y') 
         keepPrompting = false;
}

Console.WriteLine("thank you");
Run Code Online (Sandbox Code Playgroud)

goto 几乎从未在 C#(或任何其他语言)中使用过,因为当循环具有定义的流程时,很难遵循可以跳转到几乎任何位置的程序。