简体   繁体   English

无法打破 foreach 循环

[英]Cannot break out the foreach loop

I am using a collection to add a list of employees with add and display function like below:我正在使用集合添加员工列表,添加并显示 function,如下所示:

class Collection<T>
{
    static List<T> list = new List<T>();
    public Collection()
    {

    }

    public bool Add(T obj, ref T u)
    {
        list.Add(obj);  
        return true;
    }

    public void Display()
    {
        bool s = false;
        foreach (T u in list)
        {
            Console.WriteLine(u.ToString());
            s = true;
            break;
        }         
    }

And a class that contains a menu:还有一个包含菜单的 class:

public class EmployeeManagement : Employee
{
    Collection<Employee> emp = new Collection<Employee>();
    public void MainMenu()

    {
        Console.WriteLine("1. Import Employee");
        Console.WriteLine("2. Display Employee Information");
        Console.WriteLine("3. Search Employee");
        Console.WriteLine("4. Exit");
        Console.WriteLine("Enter Menu Option Number: ");
        int choice = Convert.ToInt32(Console.ReadLine());
        do
        {
            switch(choice)
            {
            case 1:
                ImportEmployee();
                break;
            case 2:
                emp.Display();
                break;
            }
        } while (true);


    }

    public void AddEmployee(Employee u)
    {
        u.InputEmployee();           
        if (!emp.Add(u))
        {
            Console.WriteLine("88");
        }
    }


    public void ImportEmployee()
    {

        while (true)
        {

            Console.WriteLine("================== Import Employee ============");
            Console.WriteLine("1. Salaried Employee");
            Console.WriteLine("2. Hourly Employee");
            Console.WriteLine("3. Main Menu");
            int choice = Convert.ToInt32(Console.ReadLine());
            if (choice == 1)
            {
                SalariedEmployee salEmployee = new SalariedEmployee();
                AddEmployee(salEmployee);
            }
            else if (choice == 2)
            {
                HourlyEmployee hourlyEmployee = new HourlyEmployee();
                AddEmployee(hourlyEmployee);
            }
            else
            {
                MainMenu();
                break;
            }
            Console.ReadKey();
        }

    }
}

I have added a new employee and it's has been added to my list.我添加了一名新员工,并且已将其添加到我的列表中。 After that, I hit option 3 to go back to the main menu and choose display employee, it kept printing my list employee and cannot break out the loop.之后,我将选项 3 打到 go 回到主菜单并选择显示员工,它一直在打印我的员工列表并且无法中断循环。 How can I fix this problem, I have tried to display in importemployee() menu and it worked without a problem.我该如何解决这个问题,我试图在 importemployee() 菜单中显示,它没有问题。

The break in the foreach loop in Display() is OK, nothing wrong there. Display() 中 foreach 循环的中断是可以的,那里没有错。 " break; " breaks out of the closest loop or a switch statement. break; ” 跳出最近的循环或 switch 语句。

Your issue is that you can't break out of the do-while in MainMenu() and that your choice will remain 2 because you are not reading the input in the do-while.您的问题是您无法在 MainMenu() 中跳出 do-while 并且您的选择将保持为 2,因为您没有在 do-while 中读取输入。

In other words, you will break out of the foreach in Display(), you'll end up in the switch in MainMenu(), you'll break out of the switch, you'll start the do-while over again and then you will enter the Display() because your choice will still be 2. This will keep repeating itself.换句话说,您将在 Display() 中跳出 foreach,最终进入 MainMenu() 中的 switch,您将跳出 switch,然后重新开始 do-while您将输入 Display(),因为您的选择仍然是 2。这将不断重复。

I've written some comments for your code so that you can follow the flow a bit easier and added some suggestions.我为您的代码写了一些注释,以便您可以更轻松地遵循流程并添加一些建议。

    public void Display()
    {
        bool s = false;
        foreach (T u in list)
        {
            Console.WriteLine(u.ToString());
            s = true;

            //Breaks out of this loop, nothing wrong here. I would use return though, if I don't have to perform any code afterwards.
            break;
        }         
    }
   public void MainMenu()
   {
        .
        .
        .

        //Only reading choice once. Would need to handle exception
        int choice = Convert.ToInt32(Console.ReadLine());
        do
        {
            //Choice will always be what you initially selected since you are not reading it inside the do-while. If you selected two it will always be two.
            switch(choice)
            {
            case 1:
                ImportEmployee();

                //Breaks out of switch statement
                break;
            case 2:
                emp.Display();

                //Breaks out of switch statement
                break;
            }

        //Infinity loop since you have no breaks for the do-while or a condition to exit it
        } while (true);
   }

My suggestion for your do-while, if you want to use do-while, would be to have it like this.如果你想使用 do-while,我对你的 do-while 的建议是这样。

        public void MainMenu()
        {
            Console.WriteLine("1. Import Employee");
            Console.WriteLine("2. Display Employee Information");
            Console.WriteLine("3. Search Employee");
            Console.WriteLine("4. Exit");
            Console.WriteLine("Enter Menu Option Number: ");

            //Default value 0
            int choice;
            do
            {
                //Use TryParse, it safely tries to interpret a string as a number. For string "s" it would return false, for string -1 it would return -1.
                //If an invalid string is entered, it will display a message, set choice to 0, go to the end of the loop then start over reading a key.
                //The entered string needs to be between the value of 1 and 4
                if (!int.TryParse(Console.ReadLine(), out choice) || choice > 4 || choice < 1)
                {
                    //We do not want to automatically trigger our switch with our previous value
                    choice = 0;

                    Console.WriteLine("Invalid menu selection, select 1-4");
                }

                switch (choice)
                {
                    case 1:
                        ImportEmployee();
                        break;
                    case 2:
                        emp.Display();
                        break;
                    case 3:
                        Console.WriteLine("Not implemented");
                        break;
                }
            } while (choice != 4); //Only stop the loop if we selected 4
        }

There are a lot of different ways to do this but this feels like a school assignment so I'm kind of just answering your question and not suggesting other improvements.有很多不同的方法可以做到这一点,但这感觉就像一个学校作业,所以我只是回答你的问题,而不是建议其他改进。

You also have quite a big issue in your "ImportEmployee()" that will be apparent when you fix the main menu loop.您的“ImportEmployee()”中还有一个相当大的问题,当您修复主菜单循环时会很明显。 If you need a hint later I'll post in comments but try to find it yourself.如果您稍后需要提示,我会在评论中发布,但请尝试自己找到。

GL总帐

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM