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

How to transfer the control of goto statement in C#

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

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;
        }
    }
}

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

我可以使用 go-to 方法吗?有什么方法可以做到这一点吗? 这里有什么问题吗?

如果你想在你的程序中使用循环,你应该使用 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");

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

你不应该用 goto 这样做。您应该始终完全避免使用 goto。如果您出于某种原因认为需要使用 goto,您应该找到一种不用 goto 的方法。这是一个如何在避免 goto.

的情况下执行此操作的示例
class Program
{
    static void Main(string[] args)
    {
        int number;
        dynamic y;

        string[] answer = new string[10];
        bool result = false;
        while(!result) {

            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();
                    }
                    break;
                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");
                    result = ((char)Console.Read()) == 'y';
                    break;
            }
        }
        Console.WriteLine("thank you");
        }
    }
}
static void Main(string[] args)
{
    // First you need a few loops, avoid goto's at all costs they make code much harder to read
    // There are better ways to do this but this will get it done
    // List<string> answer = new List<string>(); would be better here because it resizes automatically when adding
    // I left it like this because it looks like a school project
    string[] answer = new string[0]; // create variable before loops so it is not recreated on each iteration
    bool exit = false; // create bool variable and use it to exit infinite loop by setting it to true when user chooses option 4

    for (;;) // create outer infinit loop  to so the code will execute until you want you break; when option 4 is entered
    {
        int option;

        for (;;)// create infinite loop to get user input for which option they want
        {
            Console.Clear();
            Console.WriteLine("Enter the options given below\n1.Add students\n2.View all details\n3.Sorting\n4.Exit\n");
            if (int.TryParse(Console.ReadLine(), out option) && option >= 1 && option <= 4)
            { break; /*user entered valid option so we break from this infinit loop*/ }
            else
            { Console.Clear(); /*User did not enter a valid option so clear the console window*/ }
        }
        switch (option) // switch cases to handle each of the possible options entered
        {
            case 1:
                // user chose option 1
                int number = 0;
                while (number <= 0)
                {
                    Console.Clear();

                    Console.WriteLine("Enter the number of students to add.");
                    int.TryParse(Console.ReadLine(), out number);
                    answer = new string[number]; // re-initize number of students to add
                    for(int i=0;i<number;i++)
                    {
                        Console.Clear();
                        Console.WriteLine("Enter Name: ");

                        answer[i] = Console.ReadLine();
                    }
                }
                break; // break out of case 1
            case 2:
                // user chose option 2
                break;// break out of case 2
            case 3:
                // user chose option 3
                if (answer.Length > 0)
                {
                    Console.Clear();
                    Console.WriteLine("Sorted student names:");
                    Array.Sort(answer);
                    Console.WriteLine(string.Join("\n", answer));
                    Console.ReadLine(); // pause screen for reading
                }
                break;// break out of case 3
            case 4:
                // user chose option 4
                while (true) // loop until a Y or 1 is entered
                {
                    Console.WriteLine("Are you sure you want to exit\nY for YES and 1 for NO");
                    char y = (char)Console.Read();
                    if (y == 'Y' || y == 'y')
                    { exit = true; break; /*user is sure they want to exit*/ }
                    else if (y == '1')
                    { Console.Clear(); break; /*user decided not to exit*/  }
                    else
                    { Console.Clear(); }
                }
                break; // break out of case 4
        }
        if (exit) break; // if exit variable true then break out of outer infinite loop
    }
}
static void Main(string[] args)
{
    // First you need a few loops, avoid goto's at all costs they make code much harder to read
    // There are better ways to do this but this will get it done
    // List<string> answer = new List<string>(); would be better here because it resizes automatically when adding
    // I left it like this because it looks like a school project
    List<string> answer = new List<string>(); // create variable before loops so it is not recreated on each iteration
    bool exit = false; // create bool variable and use it to exit infinite loop by setting it to true when user chooses option 4

    for (;;) // create outer infinit loop  to so the code will execute until you want you break; when option 4 is entered
    {
        int option;
        for (;;)// create infinite loop to get user input for which option they want
        {
            Console.Clear();
            Console.WriteLine("Enter the options given below\n1.Add students\n2.View all details\n3.Sorting\n4.Exit\n");
            if (int.TryParse(Console.ReadLine(), out option) && option >= 1 && option <= 4)
            { break; /*user entered valid option so we break from this infinit loop*/ }
            else
            { Console.Clear(); /*User did not enter a valid option so clear the console window*/ }
        }
        switch (option) // switch cases to handle each of the possible options entered
        {
            case 1:
                // user chose option 1
                int number = 0;
                while (number <= 0)
                {
                    Console.Clear();

                    Console.WriteLine("Enter the number of students to add.");
                    int.TryParse(Console.ReadLine(), out number);
                    // Because "answer" is now a list it does not have to be sized
                    for(int i=0;i<number;i++)
                    {
                        Console.Clear();
                        Console.WriteLine("Enter Name: ");
                        // with a list, the previous list of students are not wiped out
                        // we also don't have to be carefull about writing outside array bounds because of the add method
                        answer.Add(Console.ReadLine());
                    }
                }
                break; // break out of case 1
            case 2:
                // user chose option 2
                break;// break out of case 2
            case 3:
                // user chose option 3
                if (answer.Count > 0)
                {
                    Console.Clear();
                    Console.WriteLine("Sorted student names:");
                    answer.Sort(); // List<string> have a Sort member method
                    Console.WriteLine(string.Join("\n", answer));
                }
                else
                { Console.WriteLine("No students exist to sort or list."); }

                Console.ReadLine(); // pause screen for reading
                break;// break out of case 3
            case 4:
                // user chose option 4
                while (true) // loop until a Y or 1 is entered
                {
                    Console.WriteLine("Are you sure you want to exit\nY for YES and 1 for NO");
                    char y = (char)Console.Read();
                    if (y == 'Y' || y == 'y')
                    { exit = true; break; /*user is sure they want to exit*/ }
                    else if (y == '1')
                    { Console.Clear(); break; /*user decided not to exit*/  }
                    else
                    { Console.Clear(); }
                }
                break; // break out of case 4
        }
        if (exit) break; // if exit variable true then break out of outer infinite loop
    }
}