索引器

索引器就和属性一样的  只是属性名称用this取代了

 class person
    {
        public int count
        {
            get { return _name.Length; }
        }
        private string[] _name=new string[5] {"杜伟","王玥","于海","刘海","高东" };
        //索引器其实就是一个属性,它是一个特殊的属性,常规情况下索引器其实都是一个名字叫Item的属性。

        //索引器不能写名字,要写this  后面写索引的参数
        public string this[int index]
        {
            get
            {
                if (index<0 ||index>_name.Length)
                {
                    throw new Exception();
                }
                return _name[index];
            }
            set
            {
                _name[index] = value;
            }
        }
    }
 person p = new person();
            int a = p.count;
            Console.WriteLine(a);
            p[0] = "zhans";
            for (int i = 0; i < p.count+1; i++)
            {
                Console.WriteLine(p[i]);
            }
            Console.ReadKey();

 

posted @ 2018-08-27 13:25  WhiteSpace  阅读(259)  评论(0编辑  收藏  举报