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";
        }
    }

 

相关文章:

  • 2021-08-14
  • 2021-07-04
  • 2022-12-23
  • 2022-01-10
  • 2022-12-23
  • 2021-05-25
  • 2022-12-23
猜你喜欢
  • 2021-05-27
  • 2021-10-05
  • 2022-12-23
  • 2021-09-07
  • 2021-10-15
  • 2022-02-22
相关资源
相似解决方案