Which mechanism is a better way to extend Dictionary to deal with missing keys and why?

后端 未结 3 1319
一整个雨季
一整个雨季 2021-01-04 00:48

There is a minor annoyance I find myself with a lot - I have a Dictionary that contains values that may or may not be there.

So norm

3条回答
  •  别那么骄傲
    2021-01-04 01:20

    When naming an extension method intended to replace an existing method, I tend to add to the method name for specificity rather than shortening it:

    GetValueOrDefault(...)
    

    As for the ForgivingDictionary, you can constrain TKey so that it can't be a value type. However, if you must deal with value types in it, you're going to return something for a value type and the best option is to return default(TKey) since you can't return null.

    Honestly, I'd go with the extension method.

    Edit: GetValueOrDefault(), of course, wouldn't add to the dictionary if it didn't find the key. I would just return a default value if it wasn't found, because that's how it's named. If one wanted it to insert as well, a good name would be GetValueOrInsertDefault().

提交回复
热议问题