答: C#通过提供索引器,可以象处理数组一样处理对象。特别是属性,每一个元素都以一个get或set方法暴露。索引器不单能索引数字(数组下标),还能索引一些HASHMAP的字符串,所以,通常来说,C#中类的索引器通常只有一个,就是THIS,但也可以有无数个,只要你的参数列表不同就可以了索引器和返回值无关, 索引器最大的好处是使代码看上去更自然,更符合实际的思考模式。
微软官方一个示例:
索引器允许类或结构的实例按照与数组相同的方式进行索引。 索引器类似于属性,不同之处在于它们的访问器采用参数。 在下面的示例中,定义了一个泛型类(class SampleCollection
class SampleCollection<T>{ private T[] arr = new T[100]; public T this[int i] //注意,定义索引器。this 关键字用于定义索引器。 { get { return arr[i]; //访问器采用参数 } set { arr[i] = value; //访问器采用参数 } }}class Employee { public string firstName; public string middleName; public string lastName; public string this[string index] { set { switch (index) { case "a": firstName = value; break; case "b": middleName = value; break; case "c": lastName = value; break; default: throw new ArgumentOutOfRangeException("index"); } } get { switch (index) { case "a": return firstName; case "b": return middleName; case "c": return lastName; default: throw new ArgumentOutOfRangeException("index"); } } }// This class shows how client pre uses the indexerclass Program{ static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = "Hello, World"; //这里 使用索引器进行引用 Console.WriteLine(stringCollection[0]); Employee ee = new Employee(); ee.firstName = "胡"; ee.middleName = "大"; ee.lastName = "阳"; ee["a"] = "sa"; Console.WriteLine("我的名字叫: {0}{1}{2}", ee["a"], ee["b"], ee["c"]); }}- 索引器使得对象可按照与数组相似的方法进行索引。
- get 访问器返回值。set 访问器分配值。
- this关键字用于定义索引器。
- value关键字用于定义由 set 索引器分配的值。
- 索引器不必根据整数值进行索引,由您决定如何定义特定的查找机制。
- 索引器可被重载。
- 索引器可以有多个形参,例如当访问二维数组时。



