如何制作一个高效的菜单,用户必须输入完整的选项



我正在做一个菜单屏幕,用户需要在其中输入一个选项。目前我正在做这个:

static void Start()
{
Console.WriteLine("Options: " + Environment.NewLine);
string[] options = { "Option 1", "Option 2", "Option 3" };
foreach (string value in options)
{
Console.WriteLine(value);
}
Console.Write("Type the option you want: ");
string choosen = Console.ReadLine();
if(choosen == "Option 1")
{
Console.WriteLine(Environment.NewLine + "Your choosen option was Option 1" + Environment.NewLine);
Start();
}
else if (choosen == "Option 2")
{
Console.WriteLine(Environment.NewLine + "Your choosen option was Option 2" + Environment.NewLine);
Start();
}
else if(choosen == "Option 3")
{
Console.WriteLine(Environment.NewLine + "Your choosen option was Option 3" + Environment.NewLine);
Start();
}
else
{
Console.WriteLine(Environment.NewLine + "Please choose a valid option!" + Environment.NewLine);
Start();
}
}

我可以看出这不是一种非常有效的方法,但我不知道其他方法。

我知道我可以这样做:

ConsoleKeyInfo key = Console.ReadKey();
switch (key.Key)
{
case ConsoleKey.D1:
Console.WriteLine(Environment.NewLine + "Your choosen option was Option 1" + Environment.NewLine);
Start();
break;
case ConsoleKey.D2:
Console.WriteLine(Environment.NewLine + "Your choosen option was Option 2" + Environment.NewLine);
Start();
break;
case ConsoleKey.D3:
Console.WriteLine(Environment.NewLine + "Your choosen option was Option 3" + Environment.NewLine);
Start();
break;
default:
Console.WriteLine(Environment.NewLine + "Please choose a valid option!" + Environment.NewLine);
Start();
break;
}

但我希望用户完整地写出其中一个选项,比如"选项1"左右。这样用户只需按一个键。

那么,有没有更有效的方法来做到这一点,或者为了这个确切的目的,我只能按照我一直以来的方式去做?我真的不喜欢对我的每一个选项都有一个if-else语句。

你可以试试这样的。。。

public class Option
{
public string Description { get; }
public string Method { get; }
public Option(string description, string method)
{
Description = description;
Method = method;
}
}
public class Program
{
public static void Main(string[] args)
{
var options = new[]
{
new Option("1 to print "Hello".", "PrintHello"),
new Option("2 to print "World".", "PrintWorld")
};
Console.WriteLine("Please press the number of the desired option:");
foreach (var option in options)
{
Console.WriteLine($"{option.Description}");
}
char key;
while (true)
{
key = Console.ReadKey().KeyChar;
if (key >= '1' && key <= '0' + options.Length)
{
break;
}
Console.WriteLine($"{Environment.NewLine}Please choose an option from 1 to {options.Length}");
}
Console.WriteLine($"{Environment.NewLine}You selected option {key}");
var selected = options[key - '1'];
typeof(Program).GetMethod(selected.Method).Invoke(null, null);
// This line is just to stop the console window closing
Console.ReadLine();
}
public static void PrintHello()
{
Console.WriteLine("Hello");
}
public static void PrintWorld()
{
Console.WriteLine("World");
}
}

显然,这只适用于多达9个选项。此外,如果要调用的方法不是静态的,则需要有所不同。如果是这种情况,请告诉我,我可以提供进一步的例子。

最新更新