C#索引器

//索引器:字段包含数组,为了简单访问数组字段,C#提供了索引器
// 访问修饰符 类型 this[int index,...,...]


using System;
namespace IndexerApplication
{
    class IndexedNames
    {
        class IndexTest
        {
            public int[] Id = new int[3];
            public string[] Name = new string[3];


            //Id的索引器
            public int this[int index]
            {
                get
                {
                    return Id[index];
                }
                set
                {
                    Id[index] = value;
                }
            }


            //Name的索引器
            public string this[int index,string name = "name"] /* 再加一个参数对索引器进行重载,定义出一个控制Name字段的索引器 */
            {
                get
                {
                    return Name[index];
                }
                set
                {
                    Name[index] = value;
                }
            }
        }


        static void Main(string[] args)
        {
            IndexTest test = new IndexTest();


            //访问Id索引器
            test[0] = 11;
            test[1] = 22;
            test[2] = 33;
            for (int i = 0; i <= 2; i ++)
            {
                Console.WriteLine(test[i]);
            }


            //访问Name索引器
            test[0, "name"] = "aa";
            test[1, "name"] = "bb";
            test[2, "name"] = "cc";
            for (int i = 0; i <= 2; i++)
            {
                Console.WriteLine(test[i,"name"]);
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值