日期:2014-05-17 浏览次数:20980 次
索引器(Indexer)是C#引入的一个新型的类成员,它使得对象可以像数组那样被方便,直观的引用。索引器非常类似于前面讲到的属性,但索引器可以有参数列表,且只能作用在实例对象上,而不能在类上直接作用。下面是典型的索引器的设计,在这里忽略了具体的实现。
class MyClass
{
public object this [int index]
{
get { // 取数据 }
set { // 存数据 }
}
} 索引器没有像属性和方法那样的名字,关键字this清楚地表达了索引器引用对象的特征。和属性一样,value关键字在set后的语句块里有参数传递意义。实际上从编译后的IL中间语言代码来看,上面这个索引器被实现为: class MyClass
{
public object get_Item(int index)
{ // 取数据 }
public void set_Item(int index,object value)
{//存数据 }
} using System;
class BitArray{int[] bits;
int length;
public BitArray(int length)
{ if (length < 0)
throw new ArgumentException();
bits = new int[((length - 1)>> 5) + 1];
this.length = length;
}
public int Length
{
get { return length; }
}
public bool this[int index]
{
get
{
if (index < 0 || index >=length)
throw new IndexOutOfRangeException();
else
return (bits[index >> 5] &1 << index) != 0;
}
set
{
if (index < 0 || index >=length)
throw newIndexOutOfRangeException();
else if(value)
bits[index >> 5] |= 1 <<index;
else bits[index >> 5] &= ~(1<< index);
}
}
}
class Test
{
static void Main()
{
BitArray Bits=new BitArray(10);
for(int i=0;i<10;i++)
Bits[i]=(i%2)==bsp;
Console.Write(Bits[i]+" ");
}
}编译并运行程序可以得到下面的输出: True False True FalseTrue False True False True False