1、為類或結構創建索引器
聲明索引器類型,后跟關鍵字this,然后在方括號中添加索引器參數。如
struct RawInt
{
...
public bool this[int index]
{
get{...}
set{...}
}
...
}
2、在接口中定義索引器
使用get以及/或者set關鍵字來定義一個索引器。如
interface IRawInt
{
bool this [int index]{get;set;}
}
3、在類或結構中實現一個接口索引器
如
struct RawInt:IRawInt
{
...
public bool this[int index]
{
get{...}
set{...}
}
...
}
4、在類或結構中,采取“顯式接口實現”來實現接口定義的索引器
在實現接口的類或結構中,顯式命名接口,但不要指定索引器的可訪問性。如
struct RawInt : IRawInt
{
...
bool IRawInt.this [int index]
{
get{...}
set{...}
}
...
}