VS_Saber

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
    class Animal
    {
        private Dictionary<string, int> indexer1 = new Dictionary<string, int>();
        private string[] indexer2 = new string[10];
        //从indexer1取值的索引器
        public int this[string index]
        {
            get
            {
                if (indexer1.ContainsKey(index))
                    return indexer1[index];
                else
                    throw new Exception("未找到对应值");
            }
            set
            {
                if (indexer1.ContainsKey(index))
                    indexer1[index] = value;
                else
                    indexer1.Add(index, value);
            }
        }
        //从indexer2取值的索引器
        public string this[int index]
        {
            get
            {
                if (index < 10 && !string.IsNullOrEmpty(indexer2[index]))
                    return indexer2[index];
                else if (index >= 10)
                    throw new IndexOutOfRangeException();
                else
                    throw new Exception("未找到对应值");
            }
            set
            {
                if (index < 10)
                    indexer2[index] = value;
                else
                    throw new IndexOutOfRangeException();
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Animal animal = new Animal();
            //第一个索引器
            animal["Fish"] = 20;
            animal["Tiger"] = 100;
            animal["Mouse"] = 5;
            //第二个索引器
            animal[1] = "Dog";
            animal[2] = "Cat";
            animal[3] = "Bird";
        }
    }

 

posted on 2017-12-11 20:01  小顶山人  阅读(1214)  评论(0编辑  收藏  举报