• 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;
            }
        }
  • 相关阅读:
    【BZOJ】2157: 旅游
    ValidateUtil常用验证工具类,如手机、密码、邮箱等
    Java时间格式转换大全
    springboot 使用redis
    java 判断Map集合中包含指定的键名,则返回true,否则返回false。
    Springboot 项目中引入WebSocket后,单元测试出现错误
    springboot 项目中在普通类中调用dao层的mapper 出现空指针异常
    Springboot 使用 webSocket
    微信小程序需求IIS服务器配置https关于SSL,TLS的综合解决方案
    Spring Boot使用阿里云证书启用HTTPS
  • 原文地址:https://www.cnblogs.com/chucklu/p/4468057.html
Copyright © 2020-2023  润新知