首页 技术交流 C#自定义字典类重写字典类增删改查方法 正文

C#自定义字典类重写字典类增删改查方法

发布日期:2019年06月28日 14:56        阅读次数:2144

字典类C#底层封装类:

namespace System.Collections.Generic
{
    //
    // 摘要:
    //     表示键和值的集合。若要浏览此类型的.NET Framework 源代码,请参阅 Reference Source。
    //
    // 类型参数:
    //   TKey:
    //     字典中的键的类型。
    //
    //   TValue:
    //     字典中的值的类型。
    [ComVisible(false)]
    [DebuggerDisplay("Count = {Count}")]
    [DebuggerTypeProxy(typeof(Generic.Mscorlib_DictionaryDebugView<,>))]
    [DefaultMember("Item")]
    public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, IDictionary, ICollection, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, ISerializable, IDeserializationCallback
    {
        //
        // 摘要:
        //     初始化 System.Collections.Generic.Dictionary`2 类的新实例,该实例为空,具有默认的初始容量并为键类型使用默认的相等比较器。
        public Dictionary();
        //
        // 摘要:
        //     初始化 System.Collections.Generic.Dictionary`2 类的新实例,该实例为空,具有指定的初始容量并为键类型使用默认的相等比较器。
        //
        // 参数:
        //   capacity:
        //     System.Collections.Generic.Dictionary`2 可包含的初始元素数。
        //
        // 异常:
        //   T:System.ArgumentOutOfRangeException:
        //     capacity 小于 0。
        public Dictionary(int capacity);
        //
        // 摘要:
        //     初始化 System.Collections.Generic.Dictionary`2 类的新实例,该实例为空,具有默认的初始容量并使用指定的 System.Collections.Generic.IEqualityComparer`1。
        //
        // 参数:
        //   comparer:
        //     比较键时要使用的 System.Collections.Generic.IEqualityComparer`1 实现,或者为 null,以便为键类型使用默认的
        //     System.Collections.Generic.EqualityComparer`1。
        public Dictionary(IEqualityComparer<TKey> comparer);
        //
        // 摘要:
        //     初始化 System.Collections.Generic.Dictionary`2 类的新实例,该实例包含从指定的 System.Collections.Generic.IDictionary`2
        //     复制的元素并为键类型使用默认的相等比较器。
        //
        // 参数:
        //   dictionary:
        //     System.Collections.Generic.IDictionary`2,它的元素被复制到新 System.Collections.Generic.Dictionary`2。
        //
        // 异常:
        //   T:System.ArgumentNullException:
        //     dictionary 为 null。
        //
        //   T:System.ArgumentException:
        //     dictionary 包含一个或多个重复键。
        public Dictionary(IDictionary<TKey, TValue> dictionary);
        //
        // 摘要:
        //     初始化 System.Collections.Generic.Dictionary`2 类的新实例,该实例为空,具有指定的初始容量并使用指定的 System.Collections.Generic.IEqualityComparer`1。
        //
        // 参数:
        //   capacity:
        //     System.Collections.Generic.Dictionary`2 可包含的初始元素数。
        //
        //   comparer:
        //     比较键时要使用的 System.Collections.Generic.IEqualityComparer`1 实现,或者为 null,以便为键类型使用默认的
        //     System.Collections.Generic.EqualityComparer`1。
        //
        // 异常:
        //   T:System.ArgumentOutOfRangeException:
        //     capacity 小于 0。
        public Dictionary(int capacity, IEqualityComparer<TKey> comparer);
        //
        // 摘要:
        //     初始化 System.Collections.Generic.Dictionary`2 类的新实例,该实例包含从指定的 System.Collections.Generic.IDictionary`2
        //     中复制的元素并使用指定的 System.Collections.Generic.IEqualityComparer`1。
        //
        // 参数:
        //   dictionary:
        //     System.Collections.Generic.IDictionary`2,它的元素被复制到新 System.Collections.Generic.Dictionary`2。
        //
        //   comparer:
        //     比较键时要使用的 System.Collections.Generic.IEqualityComparer`1 实现,或者为 null,以便为键类型使用默认的
        //     System.Collections.Generic.EqualityComparer`1。
        //
        // 异常:
        //   T:System.ArgumentNullException:
        //     dictionary 为 null。
        //
        //   T:System.ArgumentException:
        //     dictionary 包含一个或多个重复键。
        public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer);
        //
        // 摘要:
        //     用序列化数据初始化 System.Collections.Generic.Dictionary`2 类的新实例。
        //
        // 参数:
        //   info:
        //     一个 System.Runtime.Serialization.SerializationInfo 对象包含序列化 System.Collections.Generic.Dictionary`2
        //     所需的信息。
        //
        //   context:
        //     一个 System.Runtime.Serialization.StreamingContext 结构包含与 System.Collections.Generic.Dictionary`2
        //     关联的序列化流的源和目标。
        protected Dictionary(SerializationInfo info, StreamingContext context);

        //
        // 摘要:
        //     获取或设置与指定的键关联的值。
        //
        // 参数:
        //   key:
        //     要获取或设置的值的键。
        //
        // 返回结果:
        //     与指定的键相关联的值。如果指定键未找到,则 Get 操作引发 System.Collections.Generic.KeyNotFoundException,而
        //     Set 操作创建一个带指定键的新元素。
        //
        // 异常:
        //   T:System.ArgumentNullException:
        //     key 为 null。
        //
        //   T:System.Collections.Generic.KeyNotFoundException:
        //     已检索该属性,并且集合中不存在 key。
        public TValue this[TKey key] { get; set; }

        //
        // 摘要:
        //     获得一个包含 System.Collections.Generic.Dictionary`2 中的值的集合。
        //
        // 返回结果:
        //     一个 System.Collections.Generic.Dictionary`2.ValueCollection,包含 System.Collections.Generic.Dictionary`2
        //     中的值。
        public ValueCollection Values { get; }
        //
        // 摘要:
        //     获得一个包含 System.Collections.Generic.Dictionary`2 中的键的集合。
        //
        // 返回结果:
        //     一个 System.Collections.Generic.Dictionary`2.KeyCollection,包含 System.Collections.Generic.Dictionary`2
        //     中的键。
        public KeyCollection Keys { get; }
        //
        // 摘要:
        //     获取包含在 System.Collections.Generic.Dictionary`2 中的键/值对的数目。
        //
        // 返回结果:
        //     包含在 System.Collections.Generic.Dictionary`2 中的键/值对的数目。
        public int Count { get; }
        //
        // 摘要:
        //     获取用于确定字典中的键是否相等的 System.Collections.Generic.IEqualityComparer`1。
        //
        // 返回结果:
        //     System.Collections.Generic.IEqualityComparer`1 泛型接口实现,它用于确定当前 System.Collections.Generic.Dictionary`2
        //     中的键是否相等并为键提供哈希值。
        public IEqualityComparer<TKey> Comparer { get; }

        //
        // 摘要:
        //     将指定的键和值添加到字典中。
        //
        // 参数:
        //   key:
        //     要添加的元素的键。
        //
        //   value:
        //     要添加的元素的值。对于引用类型,该值可以为 null。
        //
        // 异常:
        //   T:System.ArgumentNullException:
        //     key 为 null。
        //
        //   T:System.ArgumentException:
        //     System.Collections.Generic.Dictionary`2 中已存在具有相同键的元素。
        public void Add(TKey key, TValue value);
        //
        // 摘要:
        //     将所有键和值从 System.Collections.Generic.Dictionary`2 中移除。
        public void Clear();
        //
        // 摘要:
        //     确定是否 System.Collections.Generic.Dictionary`2 包含指定键。
        //
        // 参数:
        //   key:
        //     要在 System.Collections.Generic.Dictionary`2 中定位的键。
        //
        // 返回结果:
        //     如果 true 包含具有指定键的元素,则为 System.Collections.Generic.Dictionary`2;否则为 false。
        //
        // 异常:
        //   T:System.ArgumentNullException:
        //     key 为 null。
        public bool ContainsKey(TKey key);
        //
        // 摘要:
        //     确定 System.Collections.Generic.Dictionary`2 是否包含特定值。
        //
        // 参数:
        //   value:
        //     要在 System.Collections.Generic.Dictionary`2 中定位的值。对于引用类型,该值可以为 null。
        //
        // 返回结果:
        //     如果 true 包含具有指定值的元素,则为 System.Collections.Generic.Dictionary`2;否则为 false。
        public bool ContainsValue(TValue value);
        //
        // 摘要:
        //     返回循环访问 System.Collections.Generic.Dictionary`2 的枚举数。
        //
        // 返回结果:
        //     用于 System.Collections.Generic.Dictionary`2 的 System.Collections.Generic.Dictionary`2.Enumerator
        //     结构。
        public Enumerator GetEnumerator();
        //
        // 摘要:
        //     实现 System.Runtime.Serialization.ISerializable 接口,并返回序列化 System.Collections.Generic.Dictionary`2
        //     实例所需的数据。
        //
        // 参数:
        //   info:
        //     System.Runtime.Serialization.SerializationInfo 对象,该对象包含序列化 System.Collections.Generic.Dictionary`2
        //     实例所需的信息。
        //
        //   context:
        //     一个 System.Runtime.Serialization.StreamingContext 结构,它包含与 System.Collections.Generic.Dictionary`2
        //     实例关联的序列化流的源和目标。
        //
        // 异常:
        //   T:System.ArgumentNullException:
        //     info 为 null。
        [SecurityCritical]
        public virtual void GetObjectData(SerializationInfo info, StreamingContext context);
        //
        // 摘要:
        //     实现 System.Runtime.Serialization.ISerializable 接口,并在完成反序列化之后引发反序列化事件。
        //
        // 参数:
        //   sender:
        //     反序列化事件源。
        //
        // 异常:
        //   T:System.Runtime.Serialization.SerializationException:
        //     与当前 System.Runtime.Serialization.SerializationInfo 实例关联的 System.Collections.Generic.Dictionary`2
        //     对象无效。
        public virtual void OnDeserialization(object sender);
        //
        // 摘要:
        //     将带有指定键的值从 System.Collections.Generic.Dictionary`2 中移除。
        //
        // 参数:
        //   key:
        //     要移除的元素的键。
        //
        // 返回结果:
        //     如果成功找到并移除该元素,则为 true;否则为 false。如果在 System.Collections.Generic.Dictionary`2 中没有找到
        //     key,则此方法返回 false。
        //
        // 异常:
        //   T:System.ArgumentNullException:
        //     key 为 null。
        public bool Remove(TKey key);
        //
        // 摘要:
        //     获取与指定键关联的值。
        //
        // 参数:
        //   key:
        //     要获取的值的键。
        //
        //   value:
        //     当此方法返回时,如果找到指定键,则包含与该键相关的值;否则包含 value 参数类型的默认值。此参数未经初始化即被传递。
        //
        // 返回结果:
        //     如果 true 包含具有指定键的元素,则为 System.Collections.Generic.Dictionary`2;否则为 false。
        //
        // 异常:
        //   T:System.ArgumentNullException:
        //     key 为 null。
        public bool TryGetValue(TKey key, out TValue value);

        //
        // 摘要:
        //     枚举 System.Collections.Generic.Dictionary`2 的元素。
        public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDisposable, IEnumerator, IDictionaryEnumerator
        {
            //
            // 摘要:
            //     获取枚举数当前位置的元素。
            //
            // 返回结果:
            //     System.Collections.Generic.Dictionary`2 中位于枚举数当前位置的元素。
            public KeyValuePair<TKey, TValue> Current { get; }

            //
            // 摘要:
            //     释放由 System.Collections.Generic.Dictionary`2.Enumerator 使用的所有资源。
            public void Dispose();
            //
            // 摘要:
            //     使枚举数前进到 System.Collections.Generic.Dictionary`2 的下一个元素。
            //
            // 返回结果:
            //     如果枚举数成功地推进到下一个元素,则为 true;如果枚举数越过集合的结尾,则为 false。
            //
            // 异常:
            //   T:System.InvalidOperationException:
            //     在创建了枚举数后集合被修改了。
            public bool MoveNext();
        }

        //
        // 摘要:
        //     表示 System.Collections.Generic.Dictionary`2 中键的集合。此类不能被继承。
        [DebuggerDisplay("Count = {Count}")]
        [DebuggerTypeProxy(typeof(Generic.Mscorlib_DictionaryKeyCollectionDebugView<,>))]
        public sealed class KeyCollection : ICollection<TKey>, IEnumerable<TKey>, IEnumerable, ICollection, IReadOnlyCollection<TKey>
        {
            //
            // 摘要:
            //     初始化 System.Collections.Generic.Dictionary`2.KeyCollection 类的新实例,该实例反映指定的 System.Collections.Generic.Dictionary`2
            //     中的键。
            //
            // 参数:
            //   dictionary:
            //     System.Collections.Generic.Dictionary`2,其键反映在新的 System.Collections.Generic.Dictionary`2.KeyCollection
            //     中。
            //
            // 异常:
            //   T:System.ArgumentNullException:
            //     dictionary 为 null。
            public KeyCollection(Dictionary<TKey, TValue> dictionary);

            //
            // 摘要:
            //     获取 System.Collections.Generic.Dictionary`2.KeyCollection 中包含的元素数。
            //
            // 返回结果:
            //     System.Collections.Generic.Dictionary`2.KeyCollection 中包含的元素个数。检索此属性的值的运算复杂度为
            //     O(1)。
            public int Count { get; }

            //
            // 摘要:
            //     从指定数组索引开始将 System.Collections.Generic.Dictionary`2.KeyCollection 元素复制到现有一维 System.Array
            //     中。
            //
            // 参数:
            //   array:
            //     作为从 System.Collections.Generic.Dictionary`2.KeyCollection 复制的元素的目标位置的一维 System.Array。System.Array
            //     必须具有从零开始的索引。
            //
            //   index:
            //     array 中从零开始的索引,从此索引处开始进行复制。
            //
            // 异常:
            //   T:System.ArgumentNullException:
            //     array 为 null。
            //
            //   T:System.ArgumentOutOfRangeException:
            //     index 小于零。
            //
            //   T:System.ArgumentException:
            //     源 System.Collections.Generic.Dictionary`2.KeyCollection 中的元素数目大于从 index 到目标 array
            //     末尾之间的可用空间。
            public void CopyTo(TKey[] array, int index);
            //
            // 摘要:
            //     返回循环访问 System.Collections.Generic.Dictionary`2.KeyCollection 的枚举数。
            //
            // 返回结果:
            //     用于 System.Collections.Generic.Dictionary`2.KeyCollection 的 System.Collections.Generic.Dictionary`2.KeyCollection.Enumerator。
            public Enumerator GetEnumerator();

            //
            // 摘要:
            //     枚举 System.Collections.Generic.Dictionary`2.KeyCollection 的元素。
            public struct Enumerator : IEnumerator<TKey>, IDisposable, IEnumerator
            {
                //
                // 摘要:
                //     获取枚举数当前位置的元素。
                //
                // 返回结果:
                //     System.Collections.Generic.Dictionary`2.KeyCollection 中位于该枚举数当前位置的元素。
                public TKey Current { get; }

                //
                // 摘要:
                //     释放由 System.Collections.Generic.Dictionary`2.KeyCollection.Enumerator 使用的所有资源。
                public void Dispose();
                //
                // 摘要:
                //     使枚举数前进到 System.Collections.Generic.Dictionary`2.KeyCollection 的下一个元素。
                //
                // 返回结果:
                //     如果枚举数已成功地推进到下一个元素,则为 true;如果枚举数传递到集合的末尾,则为 false。
                //
                // 异常:
                //   T:System.InvalidOperationException:
                //     在创建了枚举数后集合被修改了。
                public bool MoveNext();
            }
        }
        //
        // 摘要:
        //     表示 System.Collections.Generic.Dictionary`2 中值的集合。此类不能被继承。
        [DebuggerDisplay("Count = {Count}")]
        [DebuggerTypeProxy(typeof(Generic.Mscorlib_DictionaryValueCollectionDebugView<,>))]
        public sealed class ValueCollection : ICollection<TValue>, IEnumerable<TValue>, IEnumerable, ICollection, IReadOnlyCollection<TValue>
        {
            //
            // 摘要:
            //     初始化 System.Collections.Generic.Dictionary`2.ValueCollection 类的新实例,该实例反映指定的 System.Collections.Generic.Dictionary`2
            //     中的值。
            //
            // 参数:
            //   dictionary:
            //     System.Collections.Generic.Dictionary`2,其值反映在新的 System.Collections.Generic.Dictionary`2.ValueCollection
            //     中。
            //
            // 异常:
            //   T:System.ArgumentNullException:
            //     dictionary 为 null。
            public ValueCollection(Dictionary<TKey, TValue> dictionary);

            //
            // 摘要:
            //     获取 System.Collections.Generic.Dictionary`2.ValueCollection 中包含的元素数。
            //
            // 返回结果:
            //     System.Collections.Generic.Dictionary`2.ValueCollection 中包含的元素个数。
            public int Count { get; }

            //
            // 摘要:
            //     从指定数组索引开始将 System.Collections.Generic.Dictionary`2.ValueCollection 元素复制到现有一维
            //     System.Array 中。
            //
            // 参数:
            //   array:
            //     作为从 System.Collections.Generic.Dictionary`2.ValueCollection 复制的元素的目标位置的一维 System.Array。System.Array
            //     必须具有从零开始的索引。
            //
            //   index:
            //     array 中从零开始的索引,从此索引处开始进行复制。
            //
            // 异常:
            //   T:System.ArgumentNullException:
            //     array 为 null。
            //
            //   T:System.ArgumentOutOfRangeException:
            //     index 小于零。
            //
            //   T:System.ArgumentException:
            //     源 System.Collections.Generic.Dictionary`2.ValueCollection 中的元素数目大于从 index 到目标
            //     array 末尾之间的可用空间。
            public void CopyTo(TValue[] array, int index);
            //
            // 摘要:
            //     返回循环访问 System.Collections.Generic.Dictionary`2.ValueCollection 的枚举数。
            //
            // 返回结果:
            //     用于 System.Collections.Generic.Dictionary`2.ValueCollection 的 System.Collections.Generic.Dictionary`2.ValueCollection.Enumerator。
            public Enumerator GetEnumerator();

            //
            // 摘要:
            //     枚举 System.Collections.Generic.Dictionary`2.ValueCollection 的元素。
            public struct Enumerator : IEnumerator<TValue>, IDisposable, IEnumerator
            {
                //
                // 摘要:
                //     获取枚举数当前位置的元素。
                //
                // 返回结果:
                //     System.Collections.Generic.Dictionary`2.ValueCollection 中位于枚举数当前位置的元素。
                public TValue Current { get; }

                //
                // 摘要:
                //     释放由 System.Collections.Generic.Dictionary`2.ValueCollection.Enumerator 使用的所有资源。
                public void Dispose();
                //
                // 摘要:
                //     使枚举器前进到 System.Collections.Generic.Dictionary`2.ValueCollection 的下一个元素。
                //
                // 返回结果:
                //     如果枚举数成功地推进到下一个元素,则为 true;如果枚举数越过集合的结尾,则为 false。
                //
                // 异常:
                //   T:System.InvalidOperationException:
                //     在创建了枚举数后集合被修改了。
                public bool MoveNext();
            }
        }
    }
}


自定义封装类,这个是我在工作中有需求需要重写这几个方法,直接粘贴出来供大家研究沟通。

/// <summary>
    /// 自定义字典
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    public class MyDictionary<TKey, TValue> : Dictionary<TKey, TValue>
    {
        private readonly Common.Logging.ILog log = Common.Logging.LogManager.GetLogger(typeof(string));
        /// <summary>
        /// 自定义重写add方法
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public new void Add(TKey key, TValue value)
        {
            
            base.Add(key, value);
            //RedisCahingUtility.PutAliyun<MyDictionary<String, TokenPackage>>(GlobalVariables.global_redisConnstr,GlobalVariables.tempTokens);
            //log.Error(JsonHelper.LitToJson(GlobalVariables.tempTokens));
            TokenPackage obj = value as TokenPackage;
            string k = key as string;
            //log.Error(obj.CreateDate.ToString());
            RedisCahingUtility.HashSet(GlobalVariables.global_redisConnstr, k, obj);
        }
        /// <summary>
        /// 自定义重写remove方法
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public new bool Remove(TKey key)
        {
            bool r = base.Remove(key);
            //RedisCahingUtility.PutAliyun<MyDictionary<String, TokenPackage>>(GlobalVariables.global_redisConnstr, GlobalVariables.tempTokens);
             string k = key as string;
            //log.Error(obj.CreateDate.ToString());
            RedisCahingUtility.HashDelete(GlobalVariables.global_redisConnstr, k);
            return r;
        }
        /// <summary>
        /// 自定义重写属性
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public new TValue this[TKey key]
        {
            get
            {
                return base[key];//调用基类返回值方法
            }
            set
            {
                base[key] = value;//基类赋值方法
                TokenPackage obj = value as TokenPackage;
                string k = key as string;
                RedisCahingUtility.HashSet(GlobalVariables.global_redisConnstr, k, obj);//重新赋值到Redis缓存
            }
        }

  我们重写的字典类,继承了C#的字典类,所以具有了字典的所有功能,然后我们重写了这三个方法,加入我们自己的逻辑即可。                        

评论:

共 0 页 0 条记录,当前为第 1 页