嘿,我是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]);

最佳答案

您要查看ContainsKey:

if (s != null && fivewordDictionary.ContainsKey(s))
{
    Console.WriteLine(userWord + ": " + fivewordDictionary[s]);
}
else
{
    Console.WriteLine(userWord + ": not found!");
}


请注意s != null部分:如果将null传递给ContainsKey,它将抛出NullReferenceException。不好,不好,不好。

07-24 13:44