真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

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

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

“只有客戶發(fā)展了,才有我們的生存與發(fā)展!”這是創(chuàng)新互聯(lián)的服務(wù)宗旨!把網(wǎng)站當(dāng)作互聯(lián)網(wǎng)產(chǎn)品,產(chǎn)品思維更注重全局思維、需求分析和迭代思維,在網(wǎng)站建設(shè)中就是為了建設(shè)一個(gè)不僅審美在線,而且實(shí)用性極高的網(wǎng)站。創(chuàng)新互聯(lián)對(duì)成都網(wǎng)站設(shè)計(jì)、網(wǎng)站制作、外貿(mào)營(yíng)銷(xiāo)網(wǎng)站建設(shè)、網(wǎng)站制作、網(wǎng)站開(kāi)發(fā)、網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站優(yōu)化、網(wǎng)絡(luò)推廣、探索永無(wú)止境。

  接下來(lái)看一下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) HashHelpers.GetRandomizedEqualityComparer(comparer);
                Resize(entries.Length, true); 
            } 
#endif
 
        }

 2.Clear():從 Dictionary 中移除所有的鍵和值。

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 中移除所指定的鍵的值。

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)訪問(wèn) Dictionary 的枚舉器。

public Enumerator GetEnumerator() {            return new Enumerator(this, Enumerator.KeyValuePair); 
        }
[Serializable] 
        public struct Enumerator: IEnumerator>,
            IDictionaryEnumerator 
        { 
            private Dictionary dictionary;
            private int version; 
            private int index;
            private KeyValuePair current;
            private int getEnumeratorRetType;  // What should Enumerator.Current return?
 
            internal const int DictEntry = 1;
            internal const int KeyValuePair = 2; 
 
            internal Enumerator(Dictionary dictionary, int getEnumeratorRetType) {
                this.dictionary = dictionary; 
                version = dictionary.version;
                index = 0;
                this.getEnumeratorRetType = getEnumeratorRetType;
                current = new KeyValuePair(); 
            }
 
            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(dictionary.entries[index].key, dictionary.entries[index].value); 
                        index++;
                        return true; 
                    }
                    index++;
                }
 
                index = dictionary.count + 1;
                current = new KeyValuePair(); 
                return false; 
            }
 
            public KeyValuePair 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(current.Key, current.Value);
                    } 
                }
            }

            void IEnumerator.Reset() { 
                if (version != dictionary.version) {
                    ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); 
                } 

                index = 0; 
                current = new KeyValuePair();
            }

            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)單的說(shuō)明。接下來(lái)主要闡述如何創(chuàng)建安全的字典(Dictionary)存儲(chǔ)結(jié)構(gòu)。有關(guān)線程安全的部分,在這里就不再贅述了。 

    /// 
    /// 線程安全通用字典
    /// 
    /// 
    /// 
    public class TDictionary : IDictionary
    {
        /// 
        /// 鎖定字典
        /// 
        private readonly ReaderWriterLockSlim _lockDictionary = new ReaderWriterLockSlim();

        /// 
        ///基本字典
        /// 
        private readonly Dictionary _mDictionary;

        // Variables
        /// 
        /// 初始化字典對(duì)象
        /// 
        public TDictionary()
        {
            _mDictionary = new Dictionary();
        }

        /// 
        /// 初始化字典對(duì)象
        /// 
        /// 字典的初始容量
        public TDictionary(int capacity)
        {
            _mDictionary = new Dictionary(capacity);
        }

        /// 
        ///初始化字典對(duì)象
        /// 
        /// 比較器在比較鍵時(shí)使用
        public TDictionary(IEqualityComparer comparer)
        {
            _mDictionary = new Dictionary(comparer);
        }

        /// 
        /// 初始化字典對(duì)象
        /// 
        /// 其鍵和值被復(fù)制到此對(duì)象的字典
        public TDictionary(IDictionary dictionary)
        {
            _mDictionary = new Dictionary(dictionary);
        }

        /// 
        ///初始化字典對(duì)象
        /// 
        /// 字典的初始容量
        /// 比較器在比較鍵時(shí)使用
        public TDictionary(int capacity, IEqualityComparer comparer)
        {
            _mDictionary = new Dictionary(capacity, comparer);
        }

        /// 
        /// 初始化字典對(duì)象
        /// 
        /// 其鍵和值被復(fù)制到此對(duì)象的字典
        /// 比較器在比較鍵時(shí)使用
        public TDictionary(IDictionary dictionary, IEqualityComparer comparer)
        {
            _mDictionary = new Dictionary(dictionary, comparer);
        }


        /// 
        /// 返回的值. 如果 不存在被執(zhí)行并添加到字典
        /// 
        /// 檢查的關(guān)鍵
        /// 如果鍵不存在,委托調(diào)用
        public TValue GetValueAddIfNotExist(TKey key, Func func)
        {
            // 輸入寫(xiě)鎖,使絕對(duì)確定密鑰從我們檢查它是否存在的時(shí)候添加/刪除
            //到我們添加它的時(shí)間,如果它不存在
            return _lockDictionary.PerformUsingUpgradeableReadLock(() =>
            {
                TValue rVal;

                // 如果我們有值,得到它并退出
                if (_mDictionary.TryGetValue(key, out rVal))
                    return rVal;

                // 沒(méi)有找到,所以做函數(shù)得到的值
                _lockDictionary.PerformUsingWriteLock(() =>
                {
                    rVal = func.Invoke();

                    // 添加到字典
                    _mDictionary.Add(key, rVal);

                    return rVal;
                });

                return rVal;
            });
        }


        /// 
        /// 將項(xiàng)目添加到字典
        /// 
        /// 添加的關(guān)鍵
        /// 要添加的值
        public void Add(TKey key, TValue value)
        {
            _lockDictionary.PerformUsingWriteLock(() => _mDictionary.Add(key, value));
        }

        /// 
        ///將項(xiàng)目添加到字典
        /// 
        /// 要添加的鍵/值
        public void Add(KeyValuePair item)
        {
            var key = item.Key;
            var value = item.Value;
            _lockDictionary.PerformUsingWriteLock(() => _mDictionary.Add(key, value));
        }

        /// 
        /// 如果值不存在,則添加該值。 返回如果值已添加,則為true
        /// 
        /// 檢查的關(guān)鍵,添加
        /// 如果鍵不存在,則添加的值
        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;
        }

        /// 
        /// 如果鍵不存在,則添加值列表。
        /// 
        /// 要檢查的鍵,添加
        /// 如果鍵不存在,則添加的值
        public void AddIfNotExists(IEnumerable keys, TValue defaultValue)
        {
            _lockDictionary.PerformUsingWriteLock(() =>
            {
                foreach (TKey key in keys)
                {
                    // 如果不存在,則添加它
                    if (!_mDictionary.ContainsKey(key))
                        _mDictionary.Add(key, defaultValue);
                }
            });
        }

        // 添加如果不存在
        /// 
        /// 如果值不存在,則添加該值。返回值如果值已添加,則返回true。如果鍵已經(jīng)存在,則其值將更新并返回false。
        /// 
        /// 檢查的關(guān)鍵,添加
        /// 如果鍵不存在,則添加的值
        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;
        }

        /// 
        /// 如果鍵存在,則更新鍵的值。 如果更新,則返回true
        /// 
        /// 
        /// 
        public bool UpdateValueIfKeyExists(TKey key, TValue newValue)
        {
            bool rVal = false;

            _lockDictionary.PerformUsingWriteLock(() =>
            {
                // 如果我們有密鑰,然后更新它
                if (!_mDictionary.ContainsKey(key)) return;
                _mDictionary[key] = newValue;
                rVal = true;
            });

            return rVal;
        }

        /// 
        /// 如果鍵值對(duì)存在于字典中,則返回true
        /// 
        /// 鍵值對(duì)查找
        public bool Contains(KeyValuePair item)
        {
            return _lockDictionary.PerformUsingReadLock(() => ((_mDictionary.ContainsKey(item.Key)) &&
                                                               (_mDictionary.ContainsValue(item.Value))));
        }

        /// 
        /// 如果鍵存在于字典中,則返回true
        /// 
        /// 在字典中找到的關(guān)鍵
        public bool ContainsKey(TKey key)
        {
            return _lockDictionary.PerformUsingReadLock(() => _mDictionary.ContainsKey(key));
        }

        /// 
        /// 如果字典包含此值,則返回true
        /// 
        /// 找到的值
        public bool ContainsValue(TValue value)
        {
            return _lockDictionary.PerformUsingReadLock(() => _mDictionary.ContainsValue(value));
        }

        /// 
        /// 將鍵作為集合返回
        /// 
        public ICollection Keys
        {
            get { return _lockDictionary.PerformUsingReadLock(() => _mDictionary.Keys); }
        }

        /// 
        /// 刪除具有此鍵名稱的元素
        /// 
        /// 刪除的關(guān)鍵
        public bool Remove(TKey key)
        {
            return _lockDictionary.PerformUsingWriteLock(() => (!_mDictionary.ContainsKey(key)) || _mDictionary.Remove(key));
        }

        /// 
        /// 刪除具有此鍵名稱和值的元素。 返回如果項(xiàng)目已刪除,則為true。
        /// 
        /// 刪除的鍵
        public bool Remove(KeyValuePair item)
        {
            return _lockDictionary.PerformUsingWriteLock(() =>
            {
                // 如果鍵不存在則跳過(guò)
                TValue tempVal;
                if (!_mDictionary.TryGetValue(item.Key, out tempVal))
                    return false;

                //如果值不匹配,請(qǐng)?zhí)^(guò)
                return tempVal.Equals(item.Value) && _mDictionary.Remove(item.Key);
            });
        }

        /// 
        /// 從字典中刪除與模式匹配的項(xiàng)。返回true成功
        /// 
        /// 基于鍵的可選表達(dá)式
        /// 基于值的選項(xiàng)表達(dá)式
        public bool Remove(Predicate predKey, Predicate predValue)
        {
            return _lockDictionary.PerformUsingWriteLock(() =>
            {
                // 如果沒(méi)有鍵退出
                if (_mDictionary.Keys.Count == 0)
                    return true;

                //保存要?jiǎng)h除的項(xiàng)目列表
                var deleteList = new List();

                // 過(guò)程密鑰
                foreach (var key in _mDictionary.Keys)
                {
                    var isMatch = false;

                    //如果項(xiàng)匹配謂詞,則將該項(xiàng)添加到列表中
                    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;
            });
        }

        /// 
        /// 嘗試返回在元素中找到的值  如果未找到任何值,則返回false
        /// 
        /// 找到的關(guān)鍵
        /// 如果找到該鍵,則返回值
        public bool TryGetValue(TKey key, out TValue value)
        {
            _lockDictionary.EnterReadLock();
            try
            {
                return _mDictionary.TryGetValue(key, out value);
            }
            finally
            {
                _lockDictionary.ExitReadLock();
            }

        }

        // 嘗試獲取值
        /// 
        ///返回字典中值的集合
        /// 
        public ICollection Values
        {
            get { return _lockDictionary.PerformUsingReadLock(() => _mDictionary.Values); }
        }

        /// 
        /// 值 
        /// 
        /// 
        /// 
        public TValue this[TKey key]
        {
            get { return _lockDictionary.PerformUsingReadLock(() => _mDictionary[key]); }

            set { _lockDictionary.PerformUsingWriteLock(() => _mDictionary[key] = value); }
        }

        /// 
        /// 清除字典
        /// 
        public void Clear()
        {
            _lockDictionary.PerformUsingWriteLock(() => _mDictionary.Clear());
        }

        /// 
        /// 將字典的項(xiàng)目復(fù)制到鍵值對(duì)數(shù)組
        /// 
        /// 將鍵值對(duì)集合復(fù)制到
        /// 開(kāi)始復(fù)制的索引
        public void CopyTo(KeyValuePair[] array, int arrayIndex)
        {
            _lockDictionary.PerformUsingReadLock(() => _mDictionary.ToArray().CopyTo(array, arrayIndex));
        }

        /// 
        /// 返回字典中的項(xiàng)目數(shù)
        /// 
        public int Count
        {
            get { return _lockDictionary.PerformUsingReadLock(() => _mDictionary.Count); }
        }

        /// 
        ///始終返回false
        /// 
        public bool IsReadOnly
        {
            get { return false; }
        }

        /// 
        /// 枚舉器
        /// 
        /// 
        public IEnumerator> GetEnumerator()
        {
            Dictionary localDict = null;

            _lockDictionary.PerformUsingReadLock(() => localDict = new Dictionary(_mDictionary));

            // 獲取枚舉器
            return ((IEnumerable>)localDict).GetEnumerator();
        }

        /// 
        ///獲取枚舉器
        /// 
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            Dictionary localDict = null;

            _lockDictionary.PerformUsingReadLock(() => localDict = new Dictionary(_mDictionary));

            return localDict.GetEnumerator();
        }

    }

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


網(wǎng)站標(biāo)題:C#創(chuàng)建安全的字典(Dictionary)存儲(chǔ)結(jié)構(gòu)
URL網(wǎng)址:http://weahome.cn/article/giosjs.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部