gpt4 book ai didi

.net - ConcurrentDictionary 惰性添加或更新

转载 作者:行者123 更新时间:2023-12-03 20:20:26 25 4
gpt4 key购买 nike

我发现这个 C# 扩展将 GetOrAdd 转换为 Lazy,我想对 AddOrUpdate 做同样的事情。

有人可以帮我将其转换为 AddOrUpdate 吗?

 public static class ConcurrentDictionaryExtensions
{
public static TValue LazyGetOrAdd<TKey, TValue>(
this ConcurrentDictionary<TKey, Lazy<TValue>> dictionary,
TKey key,
Func<TKey, TValue> valueFactory)
{
if (dictionary == null) throw new ArgumentNullException("dictionary");
var result = dictionary.GetOrAdd(key, new Lazy<TValue>(() => valueFactory(key)));
return result.Value;
}


}

最佳答案

就是这个:

public static TValue AddOrUpdate<TKey, TValue>(this ConcurrentDictionary<TKey, Lazy<TValue>> dictionary, TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)
{
if (dictionary == null) throw new ArgumentNullException("dictionary");
var result = dictionary.AddOrUpdate(key, new Lazy<TValue>(() => addValueFactory(key)), (key2, old) => new Lazy<TValue>(() => updateValueFactory(key2, old.Value)));
return result.Value;
}

注意第二个参数的格式:一个返回一个新的 Lazy<>的委托(delegate)。对象...所以从某种角度来看,它是双重懒惰的:-)

关于.net - ConcurrentDictionary 惰性添加或更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30440638/

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