之前一直不明白什么是索引器,今天研究了一下,发现索引器一般是和数组联合使用的!
class IndexerClass
{
private int [] myArray=new int[100];
public int this[int index]
{
get
{
if (index < 0 || index >= 100)
return 0;
else
return myArray[index];
}
set
{
if (!(index <= 0 || index >= 100))
myArray[index] = value;
}
}
}
static void Main(string[] args)
{
IndexerClass b = new IndexerClass();
b[3] = 256;
b[5] = 1024;
for(int i=0;i<=5;i++)
{
Console.WriteLine("Element#{0}={1}", i, b[i]);
}
Console.ReadKey();
}
总算是明白了一些吧!还有就是发现索引器不能是static和private
也不能将ref和out作为参数传递!
OK!