c# 索引器

 public class Person
    {
        private string[] names;

        public Person(int length)
        {
            names = new string[length];
        }

        public string this[int index]
        {
            get
            {
                if (index < 0 || index > names.Length)
                {
                    throw new IndexOutOfRangeException("索引超出范围");
                }
                return names[index];
            }
            set
            {
                if (index < 0 || index > names.Length)
                {
                    throw new IndexOutOfRangeException("索引超出范围");
                }
                names[index] = value;
            }
        }
    }

 

 static void Main(string[] args)
        {
            Person p = new Person(4);
            p[0] = "wjire0";
            p[1] = "wjire1";
            p[2] = "wjire2";
            p[3] = "wjire3";
            Console.WriteLine(p[1]);
            Console.WriteLine(p[5]);     

            Console.ReadLine();
        }

 

索引器可以看成是C#开发人员对[]操作符的重载!

posted @ 2018-01-29 14:53  热敷哥  阅读(174)  评论(0编辑  收藏  举报