C#索引器的使用

本文介绍如何通过定义索引器实现数组操作,包括数组的初始化、元素的获取和设置,以及重载索引器的功能。通过示例代码演示了如何在C#中使用索引器对字符串数组进行灵活的操作。
索引器可以像数组一样的使用,在使用的时候需要先定义,定义好之后只需要创建一个对象就可以了。


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




索引器也可以进行重载


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();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值