Best way to handle a KeyNotFoundException

后端 未结 6 1462
再見小時候
再見小時候 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 02:04

    I know this is an old thread but in case it's helpful the prior answers are great, but the comments of complexity and concerns of littering the code (all valid for me also) can be addressed.

    I use a custom extension method to wrap up the complexity of the above answers in a more elegant form so that it's not littered throughout the code, and it then enables great support for null coalesce operator . . . while also maximizing performance (via above answers).

    namespace System.Collections.Generic.CustomExtensions
    {
        public static class DictionaryCustomExtensions
        {
            public static TValue GetValueSafely(this IDictionary dictionary, TKey key)
            {
                TValue value = default(TValue);
                dictionary.TryGetValue(key, out value);
                return value;
            }
        }
    }
    

    Then you can use it simply by importing the namespace System.Collections.Generic.CustomExtensions

    string value = dictionary.GetValueSafely(key) ?? "default";
    

提交回复
热议问题