use*_*322 3 .net c# dictionary
如何更改字典的工作方式,以便如果没有给定键的KVP,它会返回一个默认值,而不用通常dic["nonexistentKey"]的try-catch 包装?
你可以创建自己的类来封装 a Dictionary<TKey,TValue>和实现IDictionary<TKey,TValue>.
这将表现得像字典,但您可以编写行为以任何方式处理您不存在的键.
但是,您无法更改实际Dictionary<TKey,TValue>类的功能.
如果您愿意,还可以向IDictionary或Dictionary添加扩展方法.
public static class IDictionaryExtensions
{
public static TValue ValueAtOrDefault<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
{
if (dictionary == null || !dictionary.ContainsKey(key))
{
return defaultValue;
}
return dictionary[key];
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,ArgumentNullException如果字典为null,您可能需要抛出一个,而不是像示例中那样返回默认值...适合您的任何内容.
| 归档时间: |
|
| 查看次数: |
191 次 |
| 最近记录: |