c#从字典中获取值

Reg*_*fin 1 c# dictionary

我正在尝试制作一个基本程序,它将用户输入一个字母并输出它的莫尔斯代码等价物.我的问题是该程序似乎无法找到密钥.任何修复?请记住,我正在努力保持尽可能简单.

Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("A", ".-");
values.Add("B", "-...");
values.Add("C", "-.-.");
// ...
values.Add("8", "---..");
values.Add("9", "----.");
values.Add("0", "-----");

Console.WriteLine("Pleae enter the value you wish to convert"); 
string translate = Console.ReadLine();
string translateupper = translate.ToUpper();
if (values.ContainsKey(translateupper) == true)
{
    string Converted = (values["translateupper"].ToString());
    Console.WriteLine(Converted);
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*kiy 5

删除变量名称周围的引号:

string Converted = (values[translateupper].ToString());
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 字典条目的值是字符串 - 您不需要将其转换为字符串.
  • 为避免在字典中搜索两次条目,可以使用TryGetValue方法
  • 在C#中为变量使用camelCase名称
  • 使用字典初始值设定项为字典提供初始值
  • 考虑使用,Dictionary<char,string>因为您的密钥实际上是字符

注意事项:

var values = new Dictionary<string, string> {
      ["A"] = ".-",
      ["B"] = "-...",
      ["C"] = "-.-.",
      // etc
};

string translate = Console.ReadLine();
string converted;
if (values.TryGetValue(translate.ToUpper(), out converted))
    Console.WriteLine(converted);
// you can add 'else' block to notify user that translation was not found
Run Code Online (Sandbox Code Playgroud)

使用C#7.0,您可以声明变量.