我发现这个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;
}
}
答案 0 :(得分:1)
就是这样:
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<>
对象的委托......所以从某个角度看,它是双懒的: - )