结合“检查添加或获取”从词典(Combined “Check Add or Fetch” from Dictionary)

编程入门 行业动态 更新时间:2024-10-18 20:21:29
结合“检查添加或获取”从词典(Combined “Check Add or Fetch” from Dictionary)

我厌倦了这本词典的成语:

Dictionary<Guid,Contact> Contacts; //... if (!Contacts.ContainsKey(id)) { contact = new Contact(); Contacts[id] = contact; } else { contact = Contacts[id]; }

如果有一种语法允许新值从默认构造函数中隐式创建(如果它不存在的话)(毕竟,该字典知道值的类型)会很好。 任何人都看到了这样做的助手(如扩展方法)?

I'm tired of this dictionary idiom:

Dictionary<Guid,Contact> Contacts; //... if (!Contacts.ContainsKey(id)) { contact = new Contact(); Contacts[id] = contact; } else { contact = Contacts[id]; }

It would be nice if there was a syntax that permitted the new value to be created implicitly from a default constructor if it does not exist (the dictionary knows the type of the value, after all). Anyone seen a helper (such as an extension method) that does this?

最满意答案

执行:

public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TValue> valueCreator) { TValue value; if (!dictionary.TryGetValue(key, out value)) { value = valueCreator(); dictionary.Add(key, value); } return value; } public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key) where TValue : new() { return dictionary.GetOrAdd(key, () => new TValue()); }

用法:

var contacts = new Dictionary<Guid, Contact>(); Guid id = ... contacts.GetOrAdd(id).Name = "Abc"; // ok since Contact has public parameterless ctor contacts.GetOrAdd(id, () => new Contact { Name = "John Doe" }).Age = 40;

Implementation:

public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TValue> valueCreator) { TValue value; if (!dictionary.TryGetValue(key, out value)) { value = valueCreator(); dictionary.Add(key, value); } return value; } public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key) where TValue : new() { return dictionary.GetOrAdd(key, () => new TValue()); }

Usage:

var contacts = new Dictionary<Guid, Contact>(); Guid id = ... contacts.GetOrAdd(id).Name = "Abc"; // ok since Contact has public parameterless ctor contacts.GetOrAdd(id, () => new Contact { Name = "John Doe" }).Age = 40;

更多推荐

本文发布于:2023-08-01 15:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1359223.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词典   Combined   Check   Dictionary   Fetch

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!