Ben*_*jol 8 c# dictionary coding-style
我想要的只是一本字典,告诉我它找不到哪个键,而不仅仅是说The given key was not present in the dictionary.
我简单地考虑过做一个子类override new this[TKey key],但觉得它有点hacky,所以我已经实现了IDictionary接口,并将所有内容直接传递给内部Dictionary,并且索引器中只有其他逻辑:
public TValue this[TKey key]
{
get
{
ThrowIfKeyNotFound(key);
return _dic[key];
}
set
{
ThrowIfKeyNotFound(key);
_dic[key] = value;
}
}
private void ThrowIfKeyNotFound(TKey key)
{
if(!_dic.ContainsKey(key))
throw new ArgumentOutOfRangeException("Can't find key [" + key + "] in dictionary");
}
Run Code Online (Sandbox Code Playgroud)
这是正确的/唯一的方法吗?对这个[]的新作真的会那么糟糕吗?
Mar*_*ell 10
听起来非常适合扩展方法:
public static class SomeUtilClass {
public static TValue VerboseGetValue<TKey, TValue>(
this IDictionary<TKey, TValue> data, TKey key)
{
TValue result;
if (!data.TryGetValue(key, out result)) {
throw new KeyNotFoundException(
"Key not found: " + Convert.ToString(key));
}
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,只要您打电话VerboseGetValue,这将适用于您现有的所有词典,例如:
var data = new Dictionary<int, string> { { 123, "abc" } };
Console.WriteLine(data.VerboseGetValue(123));
Console.WriteLine(data.VerboseGetValue(456));
Run Code Online (Sandbox Code Playgroud)