using System;
using System.Collections.Generic;
using System.Text;namespace shuzutest
{
    class Program
    {
        public class A
        {
            public A(int initial)
            {
                _items = new object[initial];
               
            }
            public object this[string key]
            {
                get { return KeyToObject(key); }
                set { AddToArry(key, value); }            }
            public void AddToArry(string Key, object item)
            {
                for (int n = 0; n < _count; n++)
                {
                    shuzu pair = (shuzu)_items[n];
                    if (pair.key == Key)
                        _items[n] = new shuzu(Key, item);
                    else if (_count == _items.Length)
                        Increase();
                    _items[n] = new shuzu(Key, item);                }
            }
            protected void Increase()
            {
                int size = _items.Length + 5;
                object[] oldArray = _items;
                _items = new object[size];
                oldArray.CopyTo(_items, 0);
            }
                                protected object KeyToObject(string Key)
            {
                for (int n = 0; n < _count; n++)
                {
                    shuzu pair = (shuzu) _items[n];
                    if (pair.key == Key)
                        return pair.obj;
                }
                return null;
            }            protected struct shuzu
            {
                public shuzu(string a, object b)
                {
                    key = a;
                    obj = b;
                }
                public string key;
                public object obj;
            }
            protected object[] _items;
            protected int _count;
        }        
        static void Main(string[] args)
        {
            A a = new A(4);
            a["aaa"] = "AAA";//调用set
            a["bbb"] = "BBB";
            Console.WriteLine(a["aaa"]);//调用get
            Console.WriteLine(a["bbb"]);
           
        }
                     
    }
}

解决方案 »

  1.   

    public void AddToArry(string Key, object item)
                               }
    protected object KeyToObject(string Key)看看你这两个关键函数里的循环,因为_count一直为0,所有一次循环都没有产生,实际上你Set的时候没有成功,所以值为空
    解决办法:在你的Set方法里同步增加_count的值,Add一下,-count++,这样就能循环得起来protected int _count; 你这样声明以后,其它地方没有改变其值,它就使用编译器给他的默认值0
      

  2.   

    还有一个大问题:
     _items = new object[initial]这是你在构造函数对变量进行的初始化
    实际上这是声明了items数据的大小和类型而已,对里面的每一项,并没有进行初始化,items[0],itme[1]等的值都为null,而你后面又引用了Items[n],所以出现"未将对象引用到对象的实例"这样的错误object类型变量如果不赋值,系统会自动同初值null
    int类型变量如果不赋初值,系统会自动同初值0
    这点区别要搞清楚