索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。
在下面的示例中,定义了一个泛型类,并为其提供了简单的 get 和 set 访问器方法(作为分配和检索值的方法)。Program 类为存储字符串创建了此类的一个实例。


class
SampleCollection
<
T
>
{
private T[] arr = new T[ 100 ];
public T this [ int i]
{
get
{
return arr[i];
}
set
{
arr[i] = value;
}
}
}
// This class shows how client code uses the indexer
class Program
{
static void Main( string [] args)
{
SampleCollection < string > stringCollection = new SampleCollection < string > ();
stringCollection[ 0 ] = " Hello, World " ;
System.Console.WriteLine(stringCollection[ 0 ]);
}
}
{
private T[] arr = new T[ 100 ];
public T this [ int i]
{
get
{
return arr[i];
}
set
{
arr[i] = value;
}
}
}
// This class shows how client code uses the indexer
class Program
{
static void Main( string [] args)
{
SampleCollection < string > stringCollection = new SampleCollection < string > ();
stringCollection[ 0 ] = " Hello, World " ;
System.Console.WriteLine(stringCollection[ 0 ]);
}
}
索引器概述