ConcurrentDictionary 的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;
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM