我为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;
}
}发布于 2015-05-25 14:39:26
以下是:
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<>对象的委托.因此,从某种角度来看,它是双重懒惰的:-)
https://stackoverflow.com/questions/30440638
复制相似问题