ConcurrentDictionary<TKey, TValue>的AddOrUpdate方法

https://msdn.microsoft.com/zh-cn/library/ee378665(v=vs.110).aspx

此方法有一共有2个,现在只讨论其中一个

public TValue AddOrUpdate(
TKey key,
TValue addValue,
Func<TKey, TValue, TValue> updateValueFactory
)

 

Parameters 参数说明

key 参数名称    【此参数不允许为null】
Type: TKey 参数类型
The key to be added or whose value should be updated 需要添加或者更新的key


addValue 参数名称
Type: TValue 参数类型
The value to be added for an absent key 和新key匹配的value


updateValueFactory 参数名称    【此参数不允许为null】
Type: System.Func<TKey, TValue, TValue> 参数类型
The function used to generate a new value for an existing key based on the key's existing value 此函数用来基于已有的key的value来生成新的值


Return Value 返回值
Type: TValue 返回值的类型
The new value for the key. This will be either be addValue (if the key was absent) or the result of updateValueFactory (if the key was present).

key对应的新value,可能是新添加的,也可能是更新的

 

假定目前有一个ConcurrentDictionary<string, Dictionary<string, Color>> dictionary,需要给它添加新的值

方法1:使用委托,写一个符合委托签名的方法

private Dictionary<string,Color> Method(string deviceId,Dictionary<string,Color> dic)
{
return dic;
}

调用的时候,       dictionary.AddOrUpdate(warningInfo.DeviceID, dic, Method);   //将Method作为参数进行传递

 

方法2:使用匿名委托

dictionary.AddOrUpdate(warningInfo.DeviceID, dic, delegate(string deviceId,Dictionary<string,Color> dic1)
{
return dic1;
});

 

方法3:直接使用lambda表达式

 dictionary.AddOrUpdate(warningInfo.DeviceID, dic, (key, value) => value);

 

 

假如有多个ConcurrentDictionary的变量,都需要使用AddOrUpdate函数,并且第三个参数updateValueFactory的逻辑相同【目前假设逻辑仅仅是返回Value的值】

可以将updateValueFactory抽象成一个泛型方法来使用

复制代码
 /// <summary>
    /// GenericMethod类,用于存放泛型方法[但是这个类本身不是泛型的]
    /// </summary>
    public class GenericMethod
    {
        /// <summary>
        ///  System.Collections.Concurrent.ConcurrentDictionary类中AddOrUpdate方法中的第三个参数对应的一个泛型方法
        ///  目前的AddOrUpdate方法中的第三个三处Func委托只需要返回Value就可以了,不需要做其他的处理
        /// </summary>
        /// 参数
        /// <param name="key">第一个参数</param>
        /// <param name="value">第二个参数</param>
        /// 类型参数
        /// <typeparam name="TKey">第一个参数的类型</typeparam>
        /// <typeparam name="TValue">第二个参数的类型</typeparam>
        /// <returns></returns>
        public static TValue UpdateValueFactory<TKey, TValue>(TKey key, TValue value)
        {
            return value;
        }
    }
复制代码

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(4759)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示