Advertisement
Ilya_Bykonya

Untitled

Apr 26th, 2023
1,054
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.07 KB | Source Code | 0 0
  1. using System.Linq;
  2. using System.IO;
  3. using System;
  4. using Lab2.MenuTest;
  5.  
  6. namespace Lab2
  7. {
  8.     namespace MenuTest
  9.     {
  10.         class Menu
  11.         {
  12.             public string Title { get; }
  13.             public Dictionary<string, Action> Commands { get; } = new();
  14.             public Menu(string title) => Title = title;
  15.  
  16.             public void ProcessMenu()
  17.             {
  18.                 Console.WriteLine($"{Title}:");
  19.                 for(int index = 0; index < Commands.Count; ++index)
  20.                     Console.WriteLine($"{index} - {Commands.ElementAt(index).Key}");
  21.  
  22.                 Console.Write("Enter a command: ");
  23.                 var command = int.Parse(Console.ReadLine());
  24.                 if(command < Commands.Count && command >= 0)
  25.                 {
  26.                     Commands.ElementAt(command).Value.Invoke();
  27.                 }
  28.                 else
  29.                 {
  30.                     Console.WriteLine($"Invalid command: {command}");
  31.                 }
  32.             }
  33.         }
  34.  
  35.         class MainWindow
  36.         {
  37.             private Menu? CurrentMenu { get; set; } = null;
  38.             public MainWindow()
  39.             {
  40.                 var mainMenu = new Menu("Main menu");
  41.                 var helloworldMenu = new Menu("Helloworld");
  42.  
  43.                 mainMenu.Commands.Add("Exit", () => { System.Environment.Exit(0); });
  44.                 mainMenu.Commands.Add("To hello world", () => { SetCurrentMenu(helloworldMenu); });
  45.                 helloworldMenu.Commands.Add("Print", () => { Console.WriteLine("Hello, world"); });
  46.                 helloworldMenu.Commands.Add("To main menu", () => { SetCurrentMenu(mainMenu); });
  47.                 SetCurrentMenu(mainMenu);
  48.             }
  49.  
  50.             private void SetCurrentMenu(Menu menu) => CurrentMenu = menu;
  51.             public void ProcessEvents() => CurrentMenu?.ProcessMenu();
  52.         }
  53.     }
  54.     class Program
  55.     {
  56.         static void Main(string[] args)
  57.         {
  58.             var window = new MainWindow();
  59.             while(true)
  60.                 window.ProcessEvents();
  61.         }
  62.     }
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement