ConcurrentDictionary 惰性添加或更新

ConcurrentDictionary Lazy AddOrUpdate

我发现这个 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;
}

注意第二个参数的格式:一个代表 returns 一个新的 Lazy<> 对象...所以从某种角度来看,它是双重惰性的:-)