结合“检查添加或获取”从词典(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;更多推荐
发布评论