gpt4 book ai didi

c# - 从字典中组合 "Check Add or Fetch"

转载 作者:太空狗 更新时间:2023-10-30 00:06:23 24 4
gpt4 key购买 nike

我厌倦了这个字典习语:

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

如果有一种语法允许从默认构造函数隐式创建新值(如果它不存在)(毕竟字典知道值的类型),那就太好了。有人见过这样做的助手(例如扩展方法)吗?

最佳答案

实现:

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;

关于c# - 从字典中组合 "Check Add or Fetch",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3705950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com