索引指示器

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

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

大致结构

<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]);
}

}
}
}

posted @ 2016-07-17 12:35  隐逸天涯  阅读(355)  评论(0编辑  收藏  举报