A simple menu in a Console Application

前端 未结 3 691
清歌不尽
清歌不尽 2020-12-09 11:52

I am trying to get my menu to repeat, so after selecting and doing option 1, it will got back to the menu and ask for another option to be chosen

class Progr         


        
相关标签:
3条回答
  • 2020-12-09 12:18

    There is a nuget package for this now

    https://github.com/splttingatms/EasyConsole

    Example

    After adding the nuget package the Menu can be implemented the following way, This is a very Basic option

    static void Main(string[] args)
    {
        var menu = new EasyConsole.Menu()
          .Add("foo", () => Console.WriteLine("foo selected"))
          .Add("bar", () => Console.WriteLine("bar selected"));
        menu.Display();
    }
    

    In the action you can place Any Method to run when selected

    This will output something like this

    1. foo
    2. bar

    Choose an option:

    0 讨论(0)
  • 2020-12-09 12:27

    You can use a do while loop for the purpose Make a little modification to your DispalyMenu() method and return the result like this

    static public int DisplayMenu()
    {   
      Console.WriteLine("Football Manager");
      Console.WriteLine();
      Console.WriteLine("1. Add a Football team");
      Console.WriteLine("2. List the Football teams");
      Console.WriteLine("3. Search for a Football team");
      Console.WriteLine("4. Delete a team");
      Console.WriteLine("5. Exit");
      var result = Console.ReadLine();
      return Convert.ToInt32(result);
    }
    

    and write this in your Main() method

    int userInput = 0;
    do
    {
      userInput = DisplayMenu();
    }while(userInput!=5);
    

    So for the time being the user does not enter '5', the code will execute in the loop. Hope that helps.

    0 讨论(0)
  • 2020-12-09 12:27

    See: http://msdn.microsoft.com/en-us/library/471w8d85(v=vs.110).aspx

    Replace your main function with:

    static void Main(string[] args) {
        FootballTeams MyCode = new FootballTeams();
    
        MyCode.ListInit();
    
        ConsoleKeyInfo cki;
    
        do {
            MyCode.DisplayMenu();
            cki = Console.ReadKey(false); // show the key as you read it
            switch (cki.KeyChar.ToString()) {
                case "1":
                    MyCode.AddTeams();
                    break;
                case "2":
                    MyCode.DisplayTeams();
                    break;
                // etc..
            }
        } while (cki.Key != ConsoleKey.Escape);
    
    }
    

    Essentially, you need to loop until they press the Escape key. Each time you read the key you can execute the action selected.

    0 讨论(0)
提交回复
热议问题