泛型C#出错!

1 c# dictionary

嘿,我是C#的新手(或编程,你可以说,因为我之前只学过html和css)我正在玩仿制药,我做了一本小字典.搜索单词和东西没有问题,但是当我搜索一个与我的单词不匹配的单词时,它会抛出错误,如何解决这个问题请帮忙!

for (int i = 1; i <= 10; i++)
{
    Dictionary<string, string> fivewordDictionary = new Dictionary<string, string>();

    fivewordDictionary.Add("hello", "Saying greeting");
    fivewordDictionary.Add("bye", "Greeting when someone is leaving");
    fivewordDictionary.Add("programming", " I dont even know what it is");
    fivewordDictionary.Add("C#", "An object oriented programming language");
    Console.WriteLine();
    Console.Write("Word: ");

    string userWord = Console.ReadLine();

    Console.WriteLine();

    string s = userWord.ToLower().Trim();

    Console.WriteLine(userWord + ": " + fivewordDictionary[s]);
Run Code Online (Sandbox Code Playgroud)

Nat*_*per 5

在字典上使用TryGetValue.

var d = new Dictionary<string, int>();
d.Add("key", 0);
// This code does two hash lookups.
int value;
if (d.TryGetValue("key", out value))
{
    Console.WriteLine(value);
}
Run Code Online (Sandbox Code Playgroud)

它更有效,但更重要的是,它更具有风格和清晰.

您可避免ToLower()通过选择一个更宽松stringcomparer当你创建你的字典.

  • 比使用`ContainsKey`检查要好得多的解决方案 (2认同)