0

嘿。

我正在尝试自己学习升 C,但我在将输入作为角色时遇到了问题。我的代码部分是:

    var foodTypeMap = new Dictionary<string, string>();
    foodTypeMap["1"] = "Soups";
    foodTypeMap["2"] = "Vegetables";
    foodTypeMap["3"] = "Mains";
    foodTypeMap["4"] = "Deserts";
    ...
    ...
    string fType = Console.ReadLine();
    string dishType = " ";
    //if else statements here.. etc
    dishType = foodTypeMap[fType];

通过这种方式,我可以将 fType 获取为整数并以此初始化 discType。我想通过像 x 代表汤和 q 代表沙漠的字符来获得选择。我试过了

Using Console.ReadLine()[0]
Using Console.ReadKey().KeyChar
Using Char.TryParse()
Using Convert.ToChar()

但做不到。有没有人可以帮助我理解这一点?

4

1 回答 1

0

为了能够从字典中获取结果,您需要了解字典的工作原理。字典是键:值对。因此,如果您希望甜点为 q,则需要编辑“4”,因为这是关键,然后将其更改为 q。

var foodTypeMap = new Dictionary<string, string>();
    foodTypeMap["x"] = "Soups";
    foodTypeMap["y"] = "Vegetables";
    foodTypeMap["m"] = "Mains";
    foodTypeMap["q"] = "Deserts";
        
   var PickFromDictionary = Console.ReadLine();
        Console.WriteLine(foodTypeMap[PickFromDictionary]);

此代码将运行,如果您键入 x、y、m 或 q,您将得到其中一道菜。

foodTypeMap["x"] = "Soups";

我将 Key 值更改为 x,因此如果您现在输入 x 而不是 1,您将获得“Soups”,并且我也将其他值更改为其他字符。

如果您键入的内容不在字典中,您将收到异常

于 2021-04-18T07:47:04.237 回答