C#索引器的实现

C#索引器的结构

<modifier> <return type> this [argument list]
...{
get
...{
// Get codes goes here
}
set
...{
// Set codes goes here
}
}

注:

modifier:修饰词,如private, public, protected or internal

this:在C#中this是一个特殊的关键字,它表示引用类的当前实例。在这里它的意思是当前类的索引。

argument list:这里指索引器的参数。

具体例子:

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]);
}
}


posted @ 2012-02-14 17:01  qb371  阅读(206)  评论(0编辑  收藏  举报