在某些特定情况下,当访问字典中不存在的键时,我发现有一种简洁易读的方式来获取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;
}
实际上这并不是一个很简短的表述,当你写出像这样的东西时:
string.Format("{0}:{1};{2}:{3}",
dict.GetValueByKeyOrNull("key1"),
dict.GetValueByKeyOrNull("key2"),
dict.GetValueByKeyOrNull("key3"),
dict.GetValueByKeyOrNull("key4"));
我认为,最好有一种接近基本语法的方式: dict["key4"]
.
然后,我想到了一个使用私有字典字段的类,它可以暴露我需要的功能:
public class MyDictionary<T, U> //here I may add any of interfaces, implemented
//by dictionary itself to get an opportunity to,
//say, use foreach, etc. and implement them
// using the dictionary field.
where U : class
{
private Dictionary<T, U> dict;
public MyDictionary()
{
dict = new Dictionary<T, U>();
}
public U this[T key]
{
get
{
if (dict.ContainsKey(key))
return dict[key];
else
return null;
}
set
{
dict[key] = value;
}
}
}
但是为了获得基本行为的轻微更改,似乎有点过头了。
另一个解决方法可能是在当前上下文中定义一个Func
,像这样:
Func<string, string> GetDictValueByKeyOrNull = (key) =>
{
if (dict.ContainsKey(key))
return dict[key];
else
return null;
};
因此,它可以像GetDictValueByKeyOrNull("key1")
一样使用。
请问您能否给我更多建议或帮助我选择更好的方案?
dict.TryGetValue
呢?http://msdn.microsoft.com/en-us/library/bb347013(v=vs.110).aspx - Jess