C#基础 索引器及其重载代码示例

    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";
        }
    }
原文地址:https://www.cnblogs.com/vsSure/p/8024802.html