我想修改一個控制臺應用程式,將其模塊化(在 C# 中)。輸出應按模塊詢問輸入,以便在到達操作之前有兩個步驟。第一個是模塊,第二個是對該模塊的操作。例如電流輸出為:
1. Add a member to A
2. View all members of A
3. Add a member to B
4. View all members of B
5. Add a member to C
6. View all members of C
我正在使用 switch case 陳述句在用戶輸入中選擇一個選項并對其執行操作。模塊化后,我想得到如下輸出:
1. A
2. B
3. C
選擇 1 作為用戶輸入后,輸出應如下所示:
1.1. Add element to A
1.2. View all elements of A
對于其余的用戶輸入,依此類推。現在再次進入 1.1。或 1.2.,執行最終操作并呼叫方法。我該如何進行?
uj5u.com熱心網友回復:
如果你只想要一個簡單的切換選單,請看我的演示:
隨意根據您的需要修改此代碼。
using System;
namespace ConsoleApp5
{
internal class Program
{
static void Main(string[] args)
{
MainMenu();
Console.ReadLine();
int MainMenu()
{
while (true)
{
Console.WriteLine("\nPlease select menu item (key in 1-3): ");
Console.WriteLine("1.A");
Console.WriteLine("2.B");
Console.WriteLine("3.C");
int choice;
int.TryParse(Console.ReadLine(),out choice);
switch (choice)
{
case 1: AMenu(); break;
case 2://to do
break;
case 3://to do
break;
default: Console.WriteLine("\nInvalid input!\n"); break;
}
Console.WriteLine("\nIf you want to continue, press y, otherwise, press any other key!");
string ct = Console.ReadLine();
if (ct != "y")
break;
}
return 0;
}
int AMenu()
{
while (true)
{
Console.WriteLine("\nPlease select menu item (key in 1.1-1.2): ");
Console.WriteLine("1.1. Add element to A");
Console.WriteLine("1.2. View all elements of A");
double choice;
double.TryParse(Console.ReadLine(), out choice);
if (choice == 1.1) choice = 1;
else if (choice == 1.2) choice = 2;
switch (choice)
{
case 1: Console.WriteLine("Add element to A"); ; break;
case 2: Console.WriteLine("View all elements of A"); break;
default: Console.WriteLine("\nInvalid input!\n"); break;
}
Console.WriteLine("\nIf you want to continue, press y, otherwise, press any other key!");
string ct = Console.ReadLine();
if (ct != "y")
break;
}
return 0;
}
}
}
}
輸出:

如果您對我的代碼有任何疑問,請在下面發表評論。
uj5u.com熱心網友回復:
如果我理解正確,您想創建一個帶有子選單的互動式 CLI(命令列界面)選單。
為此,您可以在線查找具有所需功能的 C# MVC CLI 框架(一些好的谷歌搜索關鍵字可能是“ c# cli menu ”和等效的措辭)
如果你想自己實作,首先考慮 UI 和 Logic 的分離。您的 UI 類應該只關心 UI 當前狀態和用戶輸入。為了動態呼叫邏輯,View 類中的回呼字典可能是一個簡單的解決方案,如在確認后,給定當前狀態呼叫 callbacks[selection] 如果滿足條件
作為結束說明,我認為你過度設計它。因為我們談論的是 CLI,所以更簡單的縮進可以更輕松地完成任務。
1. A
1.1 view member
1.2 add member
2. B
2.1 whatever
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/424194.html
