增强版字典DictionaryEx_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > 增强版字典DictionaryEx

增强版字典DictionaryEx

 2014/6/12 19:13:22  冰麟轻武  程序员俱乐部  我要评论(0)
  • 摘要:代码publicclassDictionaryEx<TKey,TValue>:IDictionary<TKey,TValue>{///<summary>用户存储数据的字典///</summary>privateIDictionary<TKey,TValue>_items;///<summary>默认值///</summary>privateTValue_defaultValue;///<
  • 标签:

代码

class="code_img_closed" src="/Upload/Images/2014061219/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('4f8d1bbd-30c3-4db8-a8f1-30ca9bf08ba0',event)" src="/Upload/Images/2014061219/2B1B950FA3DF188F.gif" alt="" />
    public class DictionaryEx<TKey, TValue> : IDictionary<TKey, TValue>
    {
        /// <summary> 用户存储数据的字典
        /// </summary>
        private IDictionary<TKey, TValue> _items;
        /// <summary> 默认值
        /// </summary>
        private TValue _defaultValue;
        /// <summary> 用于获取值的委托
        /// </summary>
        private Converter<TKey, TValue> _getValue;
        /// <summary> 1返回_defaultValue, 2执行_getValue, 0抛出异常
        /// </summary>
        private int _mode = 0;

        #region 构造函数
        /// <summary> 初始化 DictionaryEx , key不存在时返回defaultValue
        /// </summary>
        /// <param name="defaultValue">默认值</param>
        public DictionaryEx(TValue defaultValue)
        {
            _items = new Dictionary<TKey, TValue>();
            _defaultValue = defaultValue;
            _mode = 1;
        }

        /// <summary> 初始化 DictionaryEx , key不存在时返回defaultValue
        /// </summary>
        /// <param name="defaultValue">默认值</param>
        /// <param name="comparer">比较键时要使用对象,如果为null则使用默认比较方法</param>
        public DictionaryEx(TValue defaultValue, IEqualityComparer<TKey> comparer)
        {
            _items = new Dictionary<TKey, TValue>(comparer);
            _defaultValue = defaultValue;
            _mode = 1;
        }

        /// <summary> 初始化 DictionaryEx 只读集合, key不存在时返回defaultValue
        /// </summary>
        /// <param name="defaultValue">默认值</param>
        /// <param name="dictionary">内部字典</param>
        public DictionaryEx(TValue defaultValue, IDictionary<TKey, TValue> dictionary)
        {
            Assertor.AreNull(dictionary, "dictionary");
            _items = dictionary;
            IsReadOnly = true;
            _defaultValue = defaultValue;
            _mode = 1;
        }

        /// <summary> 初始化 DictionaryEx, key不存在时返回defaultValue
        /// </summary>
        /// <param name="defaultValue">默认值</param>
        /// <param name="dictionary">内部字典</param>
        /// <param name="isReadOnly">是否只读</param>
        public DictionaryEx(TValue defaultValue, IDictionary<TKey, TValue> dictionary, bool isReadOnly)
        {
            Assertor.AreNull(dictionary, "dictionary");
            _items = dictionary;
            IsReadOnly = isReadOnly;
            _defaultValue = defaultValue;
            _mode = 1;
        }

        /// <summary> 初始化 DictionaryEx 设定getValue委托,key不存在时执行委托,并加入集合
        /// </summary>
        /// <param name="getValue">获取值的委托</param>
        public DictionaryEx(Converter<TKey, TValue> getValue)
        {
            Assertor.AreNull(getValue, "getValue");
            _items = new Dictionary<TKey, TValue>();
            _getValue = getValue;
            _mode = 2;
        }

        /// <summary> 初始化 DictionaryEx 设定getValue委托,key不存在时执行委托,并加入集合
        /// </summary>
        /// <param name="getValue">获取值的委托</param>
        /// <param name="comparer">比较键时要使用对象,如果为null则使用默认比较方法</param>
        public DictionaryEx(Converter<TKey, TValue> getValue, IEqualityComparer<TKey> comparer)
        {
            Assertor.AreNull(getValue, "getValue");
            _items = new Dictionary<TKey, TValue>(comparer);
            _getValue = getValue;
            _mode = 2;
        }

        /// <summary> 初始化 DictionaryEx 设定getValue委托,key不存在时执行委托,并加入集合
        /// </summary>
        /// <param name="getValue">获取值的委托</param>
        /// <param name="isReadOnly">集合是否限制外部修改</param>
        public DictionaryEx(Converter<TKey, TValue> getValue, bool isReadOnly)
        {
            Assertor.AreNull(getValue, "getValue");
            _items = new Dictionary<TKey, TValue>();
            _getValue = getValue;
            IsReadOnly = isReadOnly;
            _mode = 2;
        }

        /// <summary> 初始化 DictionaryEx 设定getValue委托,key不存在时执行委托,并加入集合
        /// </summary>
        /// <param name="getValue">获取值的委托</param>
        /// <param name="comparer">比较键时要使用对象</param>
        /// <param name="isReadOnly">集合是否限制外部修改</param>
        public DictionaryEx(Converter<TKey, TValue> getValue, IEqualityComparer<TKey> comparer, bool isReadOnly)
        {
            Assertor.AreNull(getValue, "getValue");
            _items = new Dictionary<TKey, TValue>(comparer);
            _getValue = getValue;
            IsReadOnly = isReadOnly;
            _mode = 2;
        }

        /// <summary> 初始化 DictionaryEx 设定getValue委托,key不存在时执行委托,并加入集合
        /// </summary>
        /// <param name="getValue">获取值的委托</param>
        /// <param name="dictionary">内部字典</param>
        public DictionaryEx(Converter<TKey, TValue> getValue, IDictionary<TKey, TValue> dictionary)
        {
            Assertor.AreNull(getValue, "getValue");
            Assertor.AreNull(dictionary, "dictionary");
            _items = dictionary;
            _getValue = getValue;
            IsReadOnly = true;
            _mode = 2;
        }

        /// <summary> 初始化 DictionaryEx 设定getValue委托,key不存在时执行委托,并加入集合
        /// </summary>
        /// <param name="getValue">获取值的委托</param>
        /// <param name="dictionary">内部字典</param>
        /// <param name="isReadOnly">是否只读</param>
        public DictionaryEx(Converter<TKey, TValue> getValue, IDictionary<TKey, TValue> dictionary, bool isReadOnly)
        {
            _items = dictionary;
            _getValue = getValue;
            IsReadOnly = isReadOnly;
            _mode = 2;
        }

        /// <summary> 初始化 DictionaryEx 只读集合
        /// </summary>
        /// <param name="dictionary">内部字典</param>
        public DictionaryEx(IDictionary<TKey, TValue> dictionary)
        {
            Assertor.AreNull(dictionary, "dictionary");
            IsReadOnly = true;
            _items = dictionary;
            _mode = 0;
        }
        #endregion

        private TValue ReturnValue(TKey key)
        {
            switch (_mode)
            {
                case 1:
                    return _defaultValue;
                case 2:
                    var value = _getValue(key);
                    lock (this)
                    {
                        _items[key] = value;
                    }
                    return value;
                default:
                    throw new KeyNotFoundException();
            }
        }

        public void Add(TKey key, TValue value)
        {
            this[key] = value;
        }

        public bool ContainsKey(TKey key)
        {
            return _items.ContainsKey(key);
        }

        public ICollection<TKey> Keys
        {
            get { return _items.Keys; }
        }

        public bool Remove(TKey key)
        {
            Assertor.AreTrue(IsReadOnly, "集合为只读");
            return _items.Remove(key);
        }

        public bool TryGetValue(TKey key, out TValue value)
        {
            return TryGetValue(key, out value);
        }

        public ICollection<TValue> Values
        {
            get { return _items.Values; }
        }

        public TValue this[TKey key]
        {
            get
            {
                TValue value;
                if (_items.TryGetValue(key, out value))
                {
                    return value;
                }
                return ReturnValue(key);
            }
            set
            {
                Assertor.AreTrue(IsReadOnly, "集合为只读");
                _items[key] = value;
            }
        }

        public void Add(KeyValuePair<TKey, TValue> item)
        {
            this[item.Key] = item.Value;
        }

        public void Clear()
        {
            Assertor.AreTrue(IsReadOnly, "集合为只读");
            _items.Clear();
        }

        public bool Contains(KeyValuePair<TKey, TValue> item)
        {
            return _items.Contains(item);
        }

        public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
        {
            ((IDictionary<TKey, TValue>)_items).CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return _items.Count; }
        }

        public bool IsReadOnly { get; private set; }

        public bool Remove(KeyValuePair<TKey, TValue> item)
        {
            return Remove(item.Key);
        }

        public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
        {
            return _items.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _items.GetEnumerator();
        }
    }
View Code

调用

        static void Main(string[] args)
        {
            //key不存在返回默认值 ,key不区分大小写 (构造函数重载可以设定内部集合,是否只读)
            var dict = new DictionaryEx<string, string>("default", StringComparer.OrdinalIgnoreCase);
            dict.Add("AAA", "aaa");
            Console.WriteLine(dict["aAa"]);  //aaa
            Console.WriteLine(dict["Bbb"]);  //default

            //key不存在,执行委托,返回value,并加入集合 , 集合本身为只读 (构造函数重载可以设定内部集合,key比较方式)
            dict = new DictionaryEx<string, string>(key => "[" + key + "]", true);
            Console.WriteLine(dict["Bbb"]); //[Bbb]
            try
            {
                dict["Bbb"] = "newvalue";       //throw new NotSupportedException("集合为只读");
            }
            catch (Exception) { }

            //创建只读键值对集合
            var innerDict = new Dictionary<string, string>();
            dict = new DictionaryEx<string, string>(innerDict);
            innerDict.Add("aaa", "aaa");
            Console.WriteLine(dict["aaa"]);
            try
            {
                dict["Bbb"] = "newvalue";       //throw new NotSupportedException("集合为只读");
            }
            catch (Exception) { }
            try
            {
                Console.WriteLine(dict["bbb"]); //throw new KeyNotFoundException();
            }
            catch (Exception) { }

        }

Code CSDN

https://code.csdn.net/snippets/389634

  • 相关文章
发表评论
用户名: 匿名