Best way to handle a KeyNotFoundException

后端 未结 6 1463
再見小時候
再見小時候 2021-01-31 01:26

I am using a dictionary to perform lookups for a program I am working on. I run a bunch of keys through the dictionary, and I expect some keys to not have a value. I catch the

6条回答
  •  春和景丽
    2021-01-31 01:49

    Use Dictionary.TryGetValue instead:

    Dictionary dictionary = new Dictionary();
    int key = 0;
    dictionary[key] = "Yes";
    
    string value;
    if (dictionary.TryGetValue(key, out value))
    {
        Console.WriteLine("Fetched value: {0}", value);
    }
    else
    {
        Console.WriteLine("No such key: {0}", key);
    }
    

提交回复
热议问题