索引指示器

官方描述:索引器允许类或结构的实例就像数组一样进行索引。索引器形态类似于,不同之处在于它们的取值函数采用参数。

这一功能在创建集合类的场合特别有用,而在其他某些情况下,比如处理大型文件或者抽象有些资源等,能让类具有类似数组行为也是非常有用的。

大致结构

<modifier><return type> this [argument list]

{

get{//读}

set{//写}

}

其中:

modifier:修饰符,如:public,private,protected

this:是C#中一个特殊的关键字,表示引用类的当前实例。这里是当前类的索引。

argument list:这里是索引器的参数

示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace suoyinzhishiqi
{
class IntIndexer
{
private string[] myData;
public IntIndexer(int size)//构造函数
{
myData =new string[size];
for(int i=0;i<myData.Length;i++)
{
myData[i]="empty";
}
}
public string this[int pos]//索引指示器
{
get { return myData[pos]; }
set { myData[pos] = value; }
}
}
class Program
{
static void Main(string[] args)
{
int size = 10;
IntIndexer myInd = new IntIndexer(size);
myInd[9] = "Some Value";
myInd[3] = "Some Value";
myInd[5] = "Some Value";
myInd[7] = "Some Value";
myInd[2] = "Some Value";
Console.WriteLine("\tIndexer Output\n");
for (int i = 0; i < size; i++)
{
Console.WriteLine("\tmyInd[{0}]:{1}", i, myInd[i]);
}

}
}
}

转载于:https://www.cnblogs.com/yinyitianya/p/5678345.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值