Добавить зацикливание для консольного меню C#
Суть моего вопроса в том, что могу ли я как-то зациклить перемещение по меню (т.е чтобы я не упирался в границы верха и низа, а перескакивал в начало/конец) не переписывая меню с case на if'ы
У меня есть код моего консольного меню (если что на gitlab'e есть проект, скину если нужно):
static void Main(string[] args)
{
int index = 0;
while (true)
{
DrawMenu(Menu.menuItems, index);
switch (Console.ReadKey(true).Key)
{
case ConsoleKey.DownArrow:
if (index < Menu.menuItems.Length - 1 || index == Menu.menuItems.Length)
index++;
break;
case ConsoleKey.UpArrow:
if (index > 0)
index--;
break;
case ConsoleKey.Enter:
switch (index)
{
case 0:
PrintPeopleList(readedPeople);
ReturnToMainMenu(Menu.menuItems, index);
break;
case 1:
PrintTimelineList(readedTimeline);
ReturnToMainMenu(Menu.menuItems, index);
break;
case 2:
PrintNamesPeople();
ReturnToMainMenu(Menu.menuItems, index);
break;
case 3:
PrintDeltaTimeline();
ReturnToMainMenu(Menu.menuItems, index);
break;
case 4:
AddNewEvent(readedPeople);
ReturnToMainMenu(Menu.menuItems, index);
break;
case 5:
AddNewPeople(readedPeople);
Console.WriteLine("Человек успешно добавлен!");
ReturnToMainMenu(Menu.menuItems, index);
break;
case 6:
Console.WriteLine("Выбран выход из приложения");
return;
}
break;
}
}
}
И метод для того, чтобы видеть перемещение по меню:
static void DrawMenu(string[] items, int index)
{
ClearScreen();
for (int i = 0; i < items.Length; i++)
{
if (i == index)
{
Console.BackgroundColor = ConsoleColor.Gray;
Console.ForegroundColor = ConsoleColor.Black;
}
Console.WriteLine(items[i]);
Console.ForegroundColor = ConsoleColor.Black;
Console.BackgroundColor = ConsoleColor.White;
}
Console.WriteLine();
}
Меню состоит из 6 пунктов, их могу прикрепить, если нужно, но чтобы вопрос был совсем огромным, пока упущу.
Ответы (1 шт):
Автор решения: aepot
→ Ссылка
Это должно было быть просто.
case ConsoleKey.DownArrow:
if (index < Menu.menuItems.Length - 1)
index++;
else
index = 0;
break;
case ConsoleKey.UpArrow:
if (index > 0)
index--;
else
index = Menu.menuItems.Length - 1;
break;
Кстати, вот это вот || index == Menu.menuItems.Length я не понимаю, зачем.