在某些情况下,当字典中没有这样的键时,对于我来说,有一个简短的,可读的方式来获取null而不是KeyNotFoundException按键访问字典值,这似乎是有用的.
我想到的第一件事是扩展方法:
public static U GetValueByKeyOrNull<T, U>(this Dictionary<T, U> dict, T key)
where U : class //it's acceptable for me to have this constraint
{
if (dict.ContainsKey(key))
return dict[key];
else
//it could be default(U) to use without U class constraint
//however, I didn't need this.
return null;
}
Run Code Online (Sandbox Code Playgroud)
但是当你写下这样的东西时,它实际上并不是很短暂的说法:
string.Format("{0}:{1};{2}:{3}",
dict.GetValueByKeyOrNull("key1"),
dict.GetValueByKeyOrNull("key2"),
dict.GetValueByKeyOrNull("key3"),
dict.GetValueByKeyOrNull("key4"));
Run Code Online (Sandbox Code Playgroud)
我会说,有一些接近基本语法的东西要好得多:dict["key4"].
然后我想出了一个带有private字典字段的类的想法,它暴露了我需要的功能:
public class MyDictionary<T, U> //here I may add any of interfaces, implemented
//by dictionary itself to …Run Code Online (Sandbox Code Playgroud)