最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#創(chuàng)建安全的字典(Dictionary)存儲(chǔ)結(jié)構(gòu)

 更新時(shí)間:2016年12月05日 16:32:59   作者:彭澤0902  
本文主要對(duì)存儲(chǔ)結(jié)構(gòu)字典(Dictionary)的一些常用方法進(jìn)行簡(jiǎn)單的說明,并闡述了如何創(chuàng)建安全的字典(Dictionary)存儲(chǔ)結(jié)構(gòu)。希望對(duì)大家有所幫助

在上面介紹過棧(Stack)的存儲(chǔ)結(jié)構(gòu),接下來介紹另一種存儲(chǔ)結(jié)構(gòu)字典(Dictionary)。 字典(Dictionary)里面的每一個(gè)元素都是一個(gè)鍵值對(duì)(由二個(gè)元素組成:鍵和值) 鍵必須是唯一的,而值不需要唯一的,鍵和值都可以是任何類型。字典(Dictionary)是常用于查找和排序的列表。

  接下來看一下Dictionary的部分方法和類的底層實(shí)現(xiàn)代碼:

  1.Add:將指定的鍵和值添加到字典中。

  public void Add(TKey key, TValue value) {
      Insert(key, value, true); 
    }
 private void Insert(TKey key, TValue value, bool add) {
       if( key == null ) { 
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
      } 
      if (buckets == null) Initialize(0);
      int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
      int targetBucket = hashCode % buckets.Length; 
#if FEATURE_RANDOMIZED_STRING_HASHING 
      int collisionCount = 0; 
#endif
      for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next) {
        if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) {
          if (add) {
            ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate); 
          }
          entries[i].value = value; 
          version++; 
          return;
        } 
#if FEATURE_RANDOMIZED_STRING_HASHING
        collisionCount++;
#endif 
      }
      int index; 
      if (freeCount > 0) { 
        index = freeList;
        freeList = entries[index].next; 
        freeCount--;
      }
      else {
        if (count == entries.Length) 
        {
          Resize(); 
          targetBucket = hashCode % buckets.Length; 
        }
        index = count; 
        count++;
      }
      entries[index].hashCode = hashCode; 
      entries[index].next = buckets[targetBucket];
      entries[index].key = key; 
      entries[index].value = value; 
      buckets[targetBucket] = index;
      version++; 
#if FEATURE_RANDOMIZED_STRING_HASHING
      if(collisionCount > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(comparer))
      { 
        comparer = (IEqualityComparer<TKey>) HashHelpers.GetRandomizedEqualityComparer(comparer);
        Resize(entries.Length, true); 
      } 
#endif
    }

  2.Clear():從 Dictionary<TKey, TValue> 中移除所有的鍵和值。

 public void Clear() {
      if (count > 0) {
        for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
        Array.Clear(entries, 0, count); 
        freeList = -1;
        count = 0; 
        freeCount = 0; 
        version++;
      } 
    }

   3.Remove():從 Dictionary<TKey, TValue> 中移除所指定的鍵的值。

 public bool Remove(TKey key) {
      if(key == null) {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
      } 
      if (buckets != null) { 
        int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; 
        int bucket = hashCode % buckets.Length;
        int last = -1; 
        for (int i = buckets[bucket]; i >= 0; last = i, i = entries[i].next) {
          if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) {
            if (last < 0) {
              buckets[bucket] = entries[i].next; 
            }
            else { 
              entries[last].next = entries[i].next; 
            }
            entries[i].hashCode = -1; 
            entries[i].next = freeList;
            entries[i].key = default(TKey);
            entries[i].value = default(TValue);
            freeList = i; 
            freeCount++;
            version++; 
            return true; 
          }
        } 
      }
      return false;
    }

  4.GetEnumerator():返回循環(huán)訪問 Dictionary<TKey, TValue> 的枚舉器。

  public Enumerator GetEnumerator() {
      return new Enumerator(this, Enumerator.KeyValuePair); 
    }
 [Serializable] 
    public struct Enumerator: IEnumerator<KeyValuePair<TKey,TValue>>,
      IDictionaryEnumerator 
    { 
      private Dictionary<TKey,TValue> dictionary;
      private int version; 
      private int index;
      private KeyValuePair<TKey,TValue> current;
      private int getEnumeratorRetType; // What should Enumerator.Current return?
      internal const int DictEntry = 1;
      internal const int KeyValuePair = 2; 
      internal Enumerator(Dictionary<TKey,TValue> dictionary, int getEnumeratorRetType) {
        this.dictionary = dictionary; 
        version = dictionary.version;
        index = 0;
        this.getEnumeratorRetType = getEnumeratorRetType;
        current = new KeyValuePair<TKey, TValue>(); 
      }
      public bool MoveNext() { 
        if (version != dictionary.version) {
          ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); 
        }
        // Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
        // dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue 
        while ((uint)index < (uint)dictionary.count) {
          if (dictionary.entries[index].hashCode >= 0) { 
            current = new KeyValuePair<TKey, TValue>(dictionary.entries[index].key, dictionary.entries[index].value); 
            index++;
            return true; 
          }
          index++;
        }
        index = dictionary.count + 1;
        current = new KeyValuePair<TKey, TValue>(); 
        return false; 
      }
      public KeyValuePair<TKey,TValue> Current {
        get { return current; }
      }
      public void Dispose() {
      } 
      object IEnumerator.Current {
        get { 
          if( index == 0 || (index == dictionary.count + 1)) {
            ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
          }
          if (getEnumeratorRetType == DictEntry) {
            return new System.Collections.DictionaryEntry(current.Key, current.Value); 
          } else { 
            return new KeyValuePair<TKey, TValue>(current.Key, current.Value);
          } 
        }
      }
      void IEnumerator.Reset() { 
        if (version != dictionary.version) {
          ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); 
        } 
        index = 0; 
        current = new KeyValuePair<TKey, TValue>();
      }
      DictionaryEntry IDictionaryEnumerator.Entry { 
        get {
          if( index == 0 || (index == dictionary.count + 1)) { 
             ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); 
          }
          return new DictionaryEntry(current.Key, current.Value);
        }
      }
      object IDictionaryEnumerator.Key {
        get { 
          if( index == 0 || (index == dictionary.count + 1)) { 
             ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
          } 
          return current.Key;
        }
      } 
      object IDictionaryEnumerator.Value { 
        get { 
          if( index == 0 || (index == dictionary.count + 1)) {
             ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); 
          }
          return current.Value;
        } 
      }
    }

     上面主要是對(duì)字典(Dictionary)的一些常用方法進(jìn)行一個(gè)簡(jiǎn)單的說明。接下來主要闡述如何創(chuàng)建安全的字典(Dictionary)存儲(chǔ)結(jié)構(gòu)。有關(guān)線程安全的部分,在這里就不再贅述了。

  /// <summary>
  /// 線程安全通用字典
  /// </summary>
  /// <typeparam name="TKey"></typeparam>
  /// <typeparam name="TValue"></typeparam>
  public class TDictionary<TKey, TValue> : IDictionary<TKey, TValue>
  {
    /// <summary>
    /// 鎖定字典
    /// </summary>
    private readonly ReaderWriterLockSlim _lockDictionary = new ReaderWriterLockSlim();
    /// <summary>
    ///基本字典
    /// </summary>
    private readonly Dictionary<TKey, TValue> _mDictionary;
    // Variables
    /// <summary>
    /// 初始化字典對(duì)象
    /// </summary>
    public TDictionary()
    {
      _mDictionary = new Dictionary<TKey, TValue>();
    }
    /// <summary>
    /// 初始化字典對(duì)象
    /// </summary>
    /// <param name="capacity">字典的初始容量</param>
    public TDictionary(int capacity)
    {
      _mDictionary = new Dictionary<TKey, TValue>(capacity);
    }
    /// <summary>
    ///初始化字典對(duì)象
    /// </summary>
    /// <param name="comparer">比較器在比較鍵時(shí)使用</param>
    public TDictionary(IEqualityComparer<TKey> comparer)
    {
      _mDictionary = new Dictionary<TKey, TValue>(comparer);
    }
    /// <summary>
    /// 初始化字典對(duì)象
    /// </summary>
    /// <param name="dictionary">其鍵和值被復(fù)制到此對(duì)象的字典</param>
    public TDictionary(IDictionary<TKey, TValue> dictionary)
    {
      _mDictionary = new Dictionary<TKey, TValue>(dictionary);
    }
    /// <summary>
    ///初始化字典對(duì)象
    /// </summary>
    /// <param name="capacity">字典的初始容量</param>
    /// <param name="comparer">比較器在比較鍵時(shí)使用</param>
    public TDictionary(int capacity, IEqualityComparer<TKey> comparer)
    {
      _mDictionary = new Dictionary<TKey, TValue>(capacity, comparer);
    }
    /// <summary>
    /// 初始化字典對(duì)象
    /// </summary>
    /// <param name="dictionary">其鍵和值被復(fù)制到此對(duì)象的字典</param>
    /// <param name="comparer">比較器在比較鍵時(shí)使用</param>
    public TDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer)
    {
      _mDictionary = new Dictionary<TKey, TValue>(dictionary, comparer);
    }
    public TValue GetValueAddIfNotExist(TKey key, Func<TValue> func)
    {
      return _lockDictionary.PerformUsingUpgradeableReadLock(() =>
      {
        TValue rVal;

        // 如果我們有值,得到它并退出
        if (_mDictionary.TryGetValue(key, out rVal))
          return rVal;
        // 沒有找到,所以做函數(shù)得到的值
        _lockDictionary.PerformUsingWriteLock(() =>
        {
          rVal = func.Invoke();
          // 添加到字典
          _mDictionary.Add(key, rVal);
          return rVal;
        });
        return rVal;
      });
    }
    /// <summary>
    /// 將項(xiàng)目添加到字典
    /// </summary>
    /// <param name="key">添加的關(guān)鍵</param>
    /// <param name="value">要添加的值</param>
    public void Add(TKey key, TValue value)
    {
      _lockDictionary.PerformUsingWriteLock(() => _mDictionary.Add(key, value));
    }
    /// <summary>
    ///將項(xiàng)目添加到字典
    /// </summary>
    /// <param name="item">要添加的鍵/值</param>
    public void Add(KeyValuePair<TKey, TValue> item)
    {
      var key = item.Key;
      var value = item.Value;
      _lockDictionary.PerformUsingWriteLock(() => _mDictionary.Add(key, value));
    }
    /// <summary>
    /// 如果值不存在,則添加該值。 返回如果值已添加,則為true
    /// </summary>
    /// <param name="key">檢查的關(guān)鍵,添加</param>
    /// <param name="value">如果鍵不存在,則添加的值</param>
    public bool AddIfNotExists(TKey key, TValue value)
    {
      bool rVal = false;
      _lockDictionary.PerformUsingWriteLock(() =>
      {
        // 如果不存在,則添加它
        if (!_mDictionary.ContainsKey(key))
        {
          // 添加該值并設(shè)置標(biāo)志
          _mDictionary.Add(key, value);
          rVal = true;
        }
      });
      return rVal;
    }
    /// <summary>
    /// 如果鍵不存在,則添加值列表。
    /// </summary>
    /// <param name="keys">要檢查的鍵,添加</param>
    /// <param name="defaultValue">如果鍵不存在,則添加的值</param>
    public void AddIfNotExists(IEnumerable<TKey> keys, TValue defaultValue)
    {
      _lockDictionary.PerformUsingWriteLock(() =>
      {
        foreach (TKey key in keys)
        {
          // 如果不存在,則添加它
          if (!_mDictionary.ContainsKey(key))
            _mDictionary.Add(key, defaultValue);
        }
      });
    }
    public bool AddIfNotExistsElseUpdate(TKey key, TValue value)
    {
      var rVal = false;
      _lockDictionary.PerformUsingWriteLock(() =>
      {
        // 如果不存在,則添加它
        if (!_mDictionary.ContainsKey(key))
        {
          // 添加該值并設(shè)置標(biāo)志
          _mDictionary.Add(key, value);
          rVal = true;
        }
        else
          _mDictionary[key] = value;
      });
      return rVal;
    }
    /// <summary>
    /// 如果鍵存在,則更新鍵的值。
    /// </summary>
    /// <param name="key"></param>
    /// <param name="newValue"></param>
    public bool UpdateValueIfKeyExists(TKey key, TValue newValue)
    {
      bool rVal = false;
      _lockDictionary.PerformUsingWriteLock(() =>
      {
        // 如果我們有密鑰,然后更新它
        if (!_mDictionary.ContainsKey(key)) return;
        _mDictionary[key] = newValue;
        rVal = true;
      });
      return rVal;
    }
    /// <summary>
    /// 如果鍵值對(duì)存在于字典中,則返回true
    /// </summary>
    /// <param name="item">鍵值對(duì)查找</param>
    public bool Contains(KeyValuePair<TKey, TValue> item)
    {
      return _lockDictionary.PerformUsingReadLock(() => ((_mDictionary.ContainsKey(item.Key)) &&
                               (_mDictionary.ContainsValue(item.Value))));
    }
    public bool ContainsKey(TKey key)
    {
      return _lockDictionary.PerformUsingReadLock(() => _mDictionary.ContainsKey(key));
    }
    /// <summary>
    /// 如果字典包含此值,則返回true
    /// </summary>
    /// <param name="value">找到的值</param>
    public bool ContainsValue(TValue value)
    {
      return _lockDictionary.PerformUsingReadLock(() => _mDictionary.ContainsValue(value));
    }
    public ICollection<TKey> Keys
    {
      get { return _lockDictionary.PerformUsingReadLock(() => _mDictionary.Keys); }
    }
    public bool Remove(TKey key)
    {
      return _lockDictionary.PerformUsingWriteLock(() => (!_mDictionary.ContainsKey(key)) || _mDictionary.Remove(key));
    }
    public bool Remove(KeyValuePair<TKey, TValue> item)
    {
      return _lockDictionary.PerformUsingWriteLock(() =>
      {
        // 如果鍵不存在則跳過
        TValue tempVal;
        if (!_mDictionary.TryGetValue(item.Key, out tempVal))
          return false;
        //如果值不匹配,請(qǐng)?zhí)^
        return tempVal.Equals(item.Value) && _mDictionary.Remove(item.Key);
      });
    }
    /// <summary>
    /// 從字典中刪除與模式匹配的項(xiàng)
    /// </summary>
    /// <param name="predKey">基于鍵的可選表達(dá)式</param>
    /// <param name="predValue">基于值的選項(xiàng)表達(dá)式</param>
    public bool Remove(Predicate<TKey> predKey, Predicate<TValue> predValue)
    {
      return _lockDictionary.PerformUsingWriteLock(() =>
      {
        // 如果沒有鍵退出
        if (_mDictionary.Keys.Count == 0)
          return true;
        //保存要?jiǎng)h除的項(xiàng)目列表
        var deleteList = new List<TKey>();
        // 過程密鑰
        foreach (var key in _mDictionary.Keys)
        {
          var isMatch = false;
          if (predKey != null)
            isMatch = (predKey(key));
          // 如果此項(xiàng)目的值匹配,請(qǐng)?zhí)砑铀?
          if ((!isMatch) && (predValue != null) && (predValue(_mDictionary[key])))
            isMatch = true;
          // 如果我們有匹配,添加到列表
          if (isMatch)
            deleteList.Add(key);
        }
        // 從列表中刪除所有項(xiàng)目
        foreach (var item in deleteList)
          _mDictionary.Remove(item);
        return true;
      });
    }
    public bool TryGetValue(TKey key, out TValue value)
    {
      _lockDictionary.EnterReadLock();
      try
      {
        return _mDictionary.TryGetValue(key, out value);
      }
      finally
      {
        _lockDictionary.ExitReadLock();
      }
    }
    public ICollection<TValue> Values
    {
      get { return _lockDictionary.PerformUsingReadLock(() => _mDictionary.Values); }
    }
    public TValue this[TKey key]
    {
      get { return _lockDictionary.PerformUsingReadLock(() => _mDictionary[key]); }
      set { _lockDictionary.PerformUsingWriteLock(() => _mDictionary[key] = value); }
    }
    /// <summary>
    /// 清除字典
    /// </summary>
    public void Clear()
    {
      _lockDictionary.PerformUsingWriteLock(() => _mDictionary.Clear());
    }
    public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
    {
      _lockDictionary.PerformUsingReadLock(() => _mDictionary.ToArray().CopyTo(array, arrayIndex));
    }
    /// <summary>
    /// 返回字典中的項(xiàng)目數(shù)
    /// </summary>
    public int Count
    {
      get { return _lockDictionary.PerformUsingReadLock(() => _mDictionary.Count); }
    }
    public bool IsReadOnly
    {
      get { return false; }
    }
    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
    {
      Dictionary<TKey, TValue> localDict = null;
      _lockDictionary.PerformUsingReadLock(() => localDict = new Dictionary<TKey, TValue>(_mDictionary));
      return ((IEnumerable<KeyValuePair<TKey, TValue>>)localDict).GetEnumerator();
    }
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
      Dictionary<TKey, TValue> localDict = null;
      _lockDictionary.PerformUsingReadLock(() => localDict = new Dictionary<TKey, TValue>(_mDictionary));
      return localDict.GetEnumerator();
    }
  }

    以上創(chuàng)建安全的字典方法中,主要對(duì)字典的一些方法和屬性進(jìn)行重寫操作,對(duì)某些方法進(jìn)行鎖設(shè)置。

    以上就是本文的全部?jī)?nèi)容,希望對(duì)大家有所幫助,同時(shí)也希望多多支持腳本之家!

相關(guān)文章

  • C#自定義控件指示燈效果

    C#自定義控件指示燈效果

    在C#中實(shí)現(xiàn)一個(gè)指示燈控件,可以通過GDI+技術(shù)繪制,首先使用Pen對(duì)象繪制外環(huán),然后用SolidBrush對(duì)象填充內(nèi)圓,通過RectangleF定義繪制和填充的邊界,控件的屬性包括顏色、間隙、外環(huán)寬度等,本文給大家介紹C#自定義控件指示燈效果,感興趣的朋友跟隨小編一起看看吧
    2024-09-09
  • C#獲取進(jìn)程的主窗口句柄的實(shí)現(xiàn)方法

    C#獲取進(jìn)程的主窗口句柄的實(shí)現(xiàn)方法

    C#獲取進(jìn)程的主窗口句柄的實(shí)現(xiàn)方法,需要的朋友可以參考一下
    2013-04-04
  • C#實(shí)現(xiàn)獲取電腦硬件顯卡核心代號(hào)信息

    C#實(shí)現(xiàn)獲取電腦硬件顯卡核心代號(hào)信息

    這篇文章主要為大家詳細(xì)介紹了如何利用C#實(shí)現(xiàn)獲取電腦硬件顯卡核心代號(hào)信息,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-01-01
  • C#中的預(yù)定義類型與引用類型

    C#中的預(yù)定義類型與引用類型

    這篇文章介紹了C#中的預(yù)定義類型與引用類型,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-05-05
  • C#運(yùn)算符大全_各種運(yùn)算符號(hào)的概述及作用

    C#運(yùn)算符大全_各種運(yùn)算符號(hào)的概述及作用

    以下是對(duì)C#中各種運(yùn)算符號(hào)的說明及作用進(jìn)行了詳細(xì)的總結(jié)介紹,需要的朋友可以過來參考下,希望對(duì)大家有所幫助
    2013-10-10
  • C#實(shí)現(xiàn)鼠標(biāo)消息捕獲

    C#實(shí)現(xiàn)鼠標(biāo)消息捕獲

    這篇文章介紹了C#實(shí)現(xiàn)鼠標(biāo)消息捕獲的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-02-02
  • 淺析C#的復(fù)制和克隆

    淺析C#的復(fù)制和克隆

    這篇文章主要介紹了淺析C#的復(fù)制和克隆,需要的朋友可以參考下
    2014-07-07
  • C#中把英文字母轉(zhuǎn)換為大寫或小寫的方法

    C#中把英文字母轉(zhuǎn)換為大寫或小寫的方法

    這篇文章主要介紹了C#中把英文字母轉(zhuǎn)換為大寫或小寫的方法,在編碼中是一個(gè)比較常用的功能,需要的朋友可以參考下
    2014-08-08
  • C#正則表達(dá)式的6個(gè)簡(jiǎn)單例子

    C#正則表達(dá)式的6個(gè)簡(jiǎn)單例子

    本文介紹了C#中的正則表達(dá)式的六個(gè)例子,都是經(jīng)常用到的,希望通過本文的介紹,能夠給你帶來收獲。
    2015-10-10
  • 使用C#判斷文件是否為圖片的多種方法

    使用C#判斷文件是否為圖片的多種方法

    在開發(fā)中,我們常需要判斷一個(gè)文件是否為圖片,這看似簡(jiǎn)單,但要實(shí)現(xiàn)得既高效又嚴(yán)謹(jǐn),需要根據(jù)不同場(chǎng)景選擇合適的方法,本文記錄了幾種常見的判斷方式,并推薦使用?SixLabors.ImageSharp?來替代已被淘汰的?System.Drawing,需要的朋友可以參考下
    2024-10-10

最新評(píng)論

延安市| 赤壁市| 广灵县| 隆回县| 武义县| 吴旗县| 本溪市| 湘乡市| 龙胜| 乐昌市| 庄河市| 东平县| 乐至县| 读书| 乌兰察布市| 呼和浩特市| 和田县| 浮山县| 长泰县| 洪江市| 鲁甸县| 呼图壁县| 鲁山县| 宝兴县| 论坛| 宣化县| 福鼎市| 仙游县| 云南省| 江川县| 平乐县| 红安县| 定陶县| 昌图县| 怀仁县| 上虞市| 南皮县| 周口市| 邓州市| 霍州市| 祁东县|