在上面介紹過(guò)棧(Stack)的存儲(chǔ)結(jié)構(gòu),接下來(lái)介紹另一種存儲(chǔ)結(jié)構(gòu)字典(Dictionary)。 字典(Dictionary)里面的每一個(gè)元素都是一個(gè)鍵值對(duì)(由二個(gè)元素組成:鍵和值) 鍵必須是唯一的,而值不需要唯一的,鍵和值都可以是任何類型。字典(Dictionary)是常用于查找和排序的列表。
在溫宿等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場(chǎng)前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供網(wǎng)站建設(shè)、成都網(wǎng)站制作 網(wǎng)站設(shè)計(jì)制作按需定制開(kāi)發(fā),公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),成都品牌網(wǎng)站建設(shè),全網(wǎng)整合營(yíng)銷推廣,成都外貿(mào)網(wǎng)站制作,溫宿網(wǎng)站建設(shè)費(fèi)用合理。接下來(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<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)訪問(wè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)單的說(shuō)明。接下來(lái)主要闡述如何創(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); } /// <summary> /// 返回的值<paramref name="key"/>. 如果 <paramref name="key"/>不存在<paramref name="func"/>被執(zhí)行并添加到字典 /// </summary> /// <param name="key">檢查的關(guān)鍵</param> /// <param name="func">如果鍵不存在,委托調(diào)用</param> public TValue GetValueAddIfNotExist(TKey key, Func<TValue> 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; }); } /// <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); } }); } // 添加如果不存在 /// <summary> /// 如果值不存在,則添加該值。返回值如果值已添加,則返回true。如果鍵已經(jīng)存在,則其值將更新并返回false。 /// </summary> /// <param name="key">檢查的關(guān)鍵,添加</param> /// <param name="value">如果鍵不存在,則添加的值</param> 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> /// 如果鍵存在,則更新鍵的值。 如果更新,則返回true /// </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)))); } /// <summary> /// 如果鍵存在于字典中,則返回true /// </summary> /// <param name="key">在字典中找到的關(guān)鍵</param> 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)); } /// <summary> /// 將鍵作為集合返回 /// </summary> public ICollection<TKey> Keys { get { return _lockDictionary.PerformUsingReadLock(() => _mDictionary.Keys); } } /// <summary> /// 刪除具有此鍵名稱的元素 /// </summary> /// <param name="key">刪除的關(guān)鍵</param> public bool Remove(TKey key) { return _lockDictionary.PerformUsingWriteLock(() => (!_mDictionary.ContainsKey(key)) || _mDictionary.Remove(key)); } /// <summary> /// 刪除具有此鍵名稱和值的元素。 返回如果項(xiàng)目已刪除,則為true。 /// </summary> /// <param name="item">刪除的鍵</param> public bool Remove(KeyValuePair<TKey, TValue> 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); }); } /// <summary> /// 從字典中刪除與模式匹配的項(xiàng)。返回true成功 /// </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(() => { // 如果沒(méi)有鍵退出 if (_mDictionary.Keys.Count == 0) return true; //保存要?jiǎng)h除的項(xiàng)目列表 var deleteList = new List<TKey>(); // 過(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; }); } /// <summary> /// 嘗試返回在元素中找到的值 <paramref name="key"/> 如果未找到任何值,則返回false /// </summary> /// <param name="key">找到的關(guān)鍵</param> /// <param name="value">如果找到該鍵,則返回值</param> public bool TryGetValue(TKey key, out TValue value) { _lockDictionary.EnterReadLock(); try { return _mDictionary.TryGetValue(key, out value); } finally { _lockDictionary.ExitReadLock(); } } // 嘗試獲取值 /// <summary> ///返回字典中值的集合 /// </summary> public ICollection<TValue> Values { get { return _lockDictionary.PerformUsingReadLock(() => _mDictionary.Values); } } /// <summary> /// 值 /// </summary> /// <param name="key"></param> /// <returns></returns> 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()); } /// <summary> /// 將字典的項(xiàng)目復(fù)制到鍵值對(duì)數(shù)組 /// </summary> /// <param name="array">將鍵值對(duì)集合復(fù)制到</param> /// <param name="arrayIndex">開(kāi)始復(fù)制的索引</param> 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); } } /// <summary> ///始終返回false /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// 枚舉器 /// </summary> /// <returns></returns> 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(); } /// <summary> ///獲取枚舉器 /// </summary> 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)行重寫(xiě)操作,對(duì)某些方法進(jìn)行鎖設(shè)置。
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。
當(dāng)前文章:C#創(chuàng)建安全的字典(Dictionary)存儲(chǔ)結(jié)構(gòu)-創(chuàng)新互聯(lián)
標(biāo)題來(lái)源:http://jinyejixie.com/article48/dphphp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導(dǎo)航、網(wǎng)站改版、動(dòng)態(tài)網(wǎng)站、自適應(yīng)網(wǎng)站、品牌網(wǎng)站設(shè)計(jì)、品牌網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容