Testing for Dictionary KeyNotFoundException

后端 未结 4 638
猫巷女王i
猫巷女王i 2021-01-26 09:51

I have a scenario where there is a dictionary that might or might not have a key value at a given time. I am presently testing to see if the value exists in the following manner

4条回答
  •  花落未央
    2021-01-26 10:42

    Take a look at the dictionary's TryGetValue method

      int myInt;
      if (!_myDictionary.TryGetValue(key, out myInt))
      {
          myInt = 0;
      }
    

    A couple of people have suggested using ContainsKey. This is not a good idea if you actually want the value because it will mean 2 lookups - e.g.

    if (_myDictionary.ContainsKey(key)) // look up 1
    {
     myInt = _myDictionary[key]; // look up 2
    }
    

提交回复
热议问题