<分区>
在某些特定情况下,在按键访问字典值时,使用一种简短易读的方式来获取 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"]
。
然后我想出了一个想法,让一个类有一个private
字典字段,它暴露了我需要的功能:
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")
那样使用。
能否请您给我更多建议或帮助我选择更好的?