C#中的索引器是新增加的,和属性有些不同。在c#中,属性可以是这样的:

  1. class Person {  
  2. private string firstname;  
  3. public string FirstName  
  4. {  
  5. get {return firstname;}  
  6.  
  7. set {firstname = value;}  
  8. }  
  9.  
  10. }  

属性声明可以如下编码:

  1. Person p = new Person();  
  2. p.FirstName = "TOM";  
  3. Console.WriteLine (p.FirstName);  

属性声明倒更像是域声明,只不过它还声明了两个特殊的成员,按照微软的说法就是所谓的访问函数(accessor)。当某一表达式的右边调用属性或者属性用作其他子程序(或者函数)的参数时即会调用get访问函数。反之,当表达式左边调用属性并且通过隐式传递value参数设置私有域值的情况下就会调用set访问函数。
索引器(Indexer)是C#引入的一个新型的类成员,它使得对象可以像数组那样被方便,直观的引用。索引器非常类似于我们前面讲到的属性,但索引器可以有参数列表,且只能作用在实例对象上,而不能在类上直接作用。下面是个例子:

  1. // consume_cs_indexers.cs  
  2. // compile with: /target:library  
  3. using System;  
  4. public class IndexerClass {  
  5. private int [] myArray = new int[100];   
  6. public int this [int index] { // Indexer declaration  
  7. get {  
  8. // Check the index limits.  
  9. if (index < 0 || index >= 100)  
  10. return 0;  
  11. else 
  12. return myArray[index];  
  13. }  
  14. set {  
  15. if (!(index < 0 || index >= 100))  
  16. myArray[index] = value;  
  17. }  
  18. }  
  19. }  
  20. /*  
  21. // code to consume the indexer  
  22. public class MainClass {  
  23. public static void Main() {  
  24. IndexerClass b = new IndexerClass();  
  25.  
  26. // Call indexer to initialize elements 3 and 5  
  27. b[3] = 256;  
  28. b[5] = 1024;  
  29. for (int i = 0 ; i <= 10 ; i++)   
  30. Console.WriteLine("Element #{0} = {1}", i, b[i]);  
  31. }  
  32. }  
  33. */