如何为用户提供一组可供选择的特定变量


Console.WriteLine("The story begins with. . . Oh yes, what is your name?");
string name = Console.ReadLine();
Console.WriteLine("Awesome! " + name + " it is then");
Console.WriteLine("This story takes place in 2077. A few years after nuclear annihilation n " +           "comes to the human race. Now we have to get you prepared for your survival n" +
"in this new wasteland until your doom is inevitably upon you. n" +
"By the way what was your profession " + name + " before the wasteland?");

因此,我的计划是给用户一组变量,例如,警察、消防员、幸存者等。这些变量已经为我可以创建的每个变量分配了预设的属性点。我只是想知道如何给他们选择。在创建这个过程中,我想我可能真的必须使用类。不过,我仍然对如何将其作为一种选择感到困惑。一旦他们决定了哪个将被控制台选中,他们就会键入名称。ReadLine((;

有很多方法可以做到这一点。这里有一个简单的例子。枚举在这里是一个有用的选择,因为它们有一个名称和数值,并且可以被视为Int32类型,因为这是它们的隐藏值。

void Main()
{
var choice = ProfessionChoice();

}

public int ProfessionChoice()
{
Console.WriteLine("Please pick from the list:nn");

foreach(var profession in Enum.GetValues(typeof(Profession)))
{
Console.WriteLine($"{(int)profession} - {profession}");
}
Console.Write("nnEnter Choice > ");
var result = Console.ReadLine();

var choice = 0;
Int32.TryParse(result, out choice);

Console.WriteLine($"nnYou picked {(Profession)choice}");

return choice;

}

public enum Profession
{
PoliceOfficer = 1,
FireFighter = 2,
Survivalist = 3
}

最新更新