+ -

索引器初探

时间:2011-06-09

来源:亦非寻常

在手机上看
手机扫描阅读

  索引器允许类或结构按照数组的形式来索引,索引器类似于属性,区别在于它们的访问器采用参数。

  索引器的格式:

  [访问修饰符] [返回类型] this[数据类型 标识符]

  如:public int this[int index]{}

  example:

namespace IndexDemo
{
class Program
{
static void Main(string[] args)
{
People p1
= new People();
p1[
2] = 6;
p1[
9] = 23;//这里分别对索引值为2和6赋值,其他的值依然保持为0。C#中int类型初始化默认为0。

for (int i = 0; i < 10; i++)
{
Console.WriteLine(p1[i]);
}
Console.ReadKey();
}
}

internal class People
{
int[] arr = new int[100];
public int this[int index]
{
get
{
if (index >= 100 || index < 0)
{
return 0;
}
else
{
return arr[index];
}
}

set
{
arr[index]
= value;
}

}
}
}

输出值为:

0
0
6
0
0
0
0
0
0
23

热门下载

更多