C#的索引器

我们已经很习惯在使用数组或者集合的时候,通过索引号引用他们中的某个成员。如果我们需要为自己的类型实现同样的功能,那么可以参考下面的例子

    class Program
    {
        static void Main(string[] args)
        {
            Customers cs = new Customers();
            Customer c = new Customer();

            c.CustomerID = 1;
            cs.Items = new List<Customer>();
            cs.Items.Add(c);

            Console.WriteLine(cs[0].CustomerID);
           Console.Read();


        }
    }

    class Customers
    {
        

        public List<Customer> Items { get; set; }
        /// <summary>
        /// 这个属性比较特殊,其实就是所谓的索引器
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public Customer this[int index] {
            get {
                return Items[index];
            }
        }
    }

    class Customer
    {
        public int CustomerID { get; set; }
    }
如你所见,定义一个索引器并不复杂。它其实就是一个属性,但是用一个特殊的写法:this[int index]来作为属性名称
public Customer this[int index] { get { return Items[index]; } } 
原文地址:https://www.cnblogs.com/chenxizhang/p/1290877.html