【发布时间】:2011-03-08 03:37:01
【问题描述】:
我们想使用键索引将项目分配/添加到字典,如下所示:
Dictionary<string, object> dict = new Dictionary<string, object>();
dict["key"] = dict["key"] ?? "object";
但它会导致:“字典中不存在给定的键。”
有什么方法可以像我为会话分配值一样,使用 null 合并:
Session["Member"] = Session["Member"] ?? new Member();
谢谢
编辑: 我实际上试图从子类字典中覆盖索引器,但无济于事。 实现 IDictionary 接口似乎太多了,因为我们只需要下面代码的功能(即,如果找不到键,则返回 null)。 所以我想,也许我们可以使用如下扩展:
public static TValue [this Dictionary<TKey, TValue> thisDictionary, TKey key] {
get { return thisDictionary.ContainsKey(key) ? thisDictionary[key] : null; }
set { thisDictionary[key] = value; }
}
但它无法正常工作,甚至无法编译。
还有其他更简单的方法可以让我们重用这个索引器功能吗?非常感谢。
【问题讨论】:
标签: dictionary c#-4.0 key key-value null-coalescing-operator