让C#类支持关联数组

using System;
using System.Collections;
using System.Collections.Generic;

namespace ConsoleApplication1
{

    class Program
    {
        static void Main(string[] args)
        {
            TestClass t = new TestClass();

            //添加遍历
            t["aaa"] = "111";
            t["bbb"] = "222";
            t["ccc"] = "333";
            foreach (string item in t)
            {
                Console.WriteLine(item + "=" + t[item]);
            }

            //删除再遍历
            t["bbb"] = null;
            foreach (string item in t)
            {
                Console.WriteLine(item + "=" + t[item]);
            }

            Console.ReadKey();
        }
    }

    /// <summary>
    /// 实现关联数组的类
    /// </summary>
    class TestClass : IEnumerable, IEnumerator
    {
        Dictionary<string, string> _dict = new Dictionary<string, string>();
        List<string> _list = new List<string>();

        public TestClass()
        { }

        public string this[string name]
        {
            get
            {
                if (_dict.ContainsKey(name))
                    return _dict[name];
                else
                    return string.Empty;
            }
            set
            {
                if (string.IsNullOrEmpty(name))
                    throw new ArgumentException("键不能为空。");
                else
                {
                    if (!_dict.ContainsKey(name))
                    {
                        _dict.Add(name, value);
                        _list.Add(name);
                    }
                    else
                    {
                        if (value == null || string.IsNullOrEmpty(value)) //值为空时删除
                        {
                            _dict.Remove(name);
                            _list.Remove(name);
                        }
                        else
                        {
                            _dict[name] = value;
                        }
                    }
                }
            }
        }

        //IEnumerable实现部分

        public IEnumerator GetEnumerator()
        {
            return (IEnumerator)this;
        }

        //IEnumerator实现部分

        private int position = -1;
        public bool MoveNext()
        {
            position++;
            if (position < _list.Count)
                return true;
            else
            {
                Reset();
                return false;
            }
        }

        public void Reset()
        {
            position = -1;
        }

        public object Current
        {
            get
            {
                try
                {
                    return _list[position];
                }
                catch (IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }

    }

}


评论: 0 | 引用: 0 | 查看次数: 6355
发表评论
登录后再发表评论!