C#索引器的使用

来源:互联网 发布:全国软件测试大赛 编辑:程序博客网 时间:2024/05/16 14:40
索引器可以像数组一样的使用,在使用的时候需要先定义,定义好之后只需要创建一个对象就可以了。


也就是说你可以使用一个对象进行不同的操作。也就是将一个实例对象划分成更小的部分了。




索引器也可以进行重载


using System;




namespace IndexerApplication
{
    class IndexedNames
    {
        private string[] namelist = new string[size];
        static public int size = 10;
        //构造函数
        public IndexedNames()
        {
            //初始化字符串数组
            for (int i = 0; i < size; i++)
                namelist[i] = "N. A.";
        }
        //定义一个索引器
        public string this[int index]
        {
            //获取值
            get
            {
                string tmp;


                if (index >= 0 && index <= size - 1)
                {
                    tmp = namelist[index];
                }
                else
                {
                    tmp = "";
                }


                return (tmp);
            }


            //设置值
            set
            {
                if (index >= 0 && index <= size - 1)
                {
                    namelist[index] = value;
                }
            }
        }


        static void Main(string[] args)
        {
            IndexedNames names = new IndexedNames();
            names[0] = "Zara";
            names[1] = "Riz";
            names[2] = "Nuha";
            names[3] = "Asif";
            names[4] = "Davinder";
            names[5] = "Sunil";
            names[6] = "Rubic";
            names[9] = "stywen";
            for (int i = 0; i < IndexedNames.size; i++)
            {
                Console.WriteLine(names[i]);
            }
            Console.ReadKey();
        }
    }
}
0 0
原创粉丝点击