当我执行 val = dict["nonexistent key"] 时,我得到 System.Collections.Generic.KeyNotFoundException 有没有办法让我的字典以键作为参数调用成员函数来生成值?
-编辑- 也许我应该更具体一些。我想自动调用一个成员函数来做它需要的事情,为该键创建适当的值。在这种情况下,它会在我的数据库中创建一个条目,然后返回给我它的唯一句柄。我将在下面发布我的解决方案。
最佳答案
使用扩展方法:
static class DictionaryExtensions {
public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey,TValue> dic, TKey key, Func<TKey, TValue> valueGenerator) {
TValue val;
if (dic.TryGetValue(key, out val))
return val;
return valueGenerator(key);
}
}
你可以调用它:
dic.GetValueOrDefault("nonexistent key", key => "null");
或者传递一个成员函数:
dic.GetValueOrDefault("nonexistent key", MyMemberFunction);
关于C# 字典 <> 缺少键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/718610/