关于索引器

索引器这个东东,我也是最近才接触,一般所说的索引器,是指定义在某个类里面的一个类似属性的东西。索引器是.net中新的类成员。类似与类的属性。有些人干脆称呼它为带参数的属性。

索引器可以快速定位到类中某一个数组成员的单元。下面看看代码:

Indexer 
class indexerClass
{
private int[] arr=new int[100];
private string[] names=new string[100];
public int this[int index]
{
get
{
if (index < 0 || index >= 100)
{
return -1;
}
else
{
return arr[index];
}
}
set//索引器的get,set被编译器编译成get_item,sge_item方法。
{
if (index >=0 && index < 100)
{
arr[index]
=value;
}
}
}
public int this[string key]//索引器的参数也可是字符串等,不一定只能是int
{
get
{
return GetNumber(key);
}
}
public int GetNumber(string Gender)
{
if (Gender == "boy")
{
return 1;
}
else if (Gender == "girl")
{
return 0;
}
else
{
return -1;
}
}
}

索引器参数大多是int类型,但也可以是其他类型,如string。

static void Main(string[] args)
{
indexerClass indexerTest
= new indexerClass();
for (int i = 0; i < 10; i++)
{
indexerTest[i]
= i + 2; //对类的对象,可以直接像操作数组一样操作对象里面的数组。
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine(indexerTest[i]);
}
Console.ReadKey();
}
作者:GY小小鸟
         
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/YangFengHui/p/2018942.html