一、 索引器定义:

索引器允许类或结构的实例就像数组一样进行索引。

二、 索引器使用

索引器经常是在主要用于封装内部集合或数组的类型中实现的。

C# 并不将索引类型限制为整数

三、 接口索引器与类索引器的区别:

接口访问器不使用修饰符。

接口访问器没有体。

四、 索引器与属性的区别:

索引器与属性类似。 除下表中显示的差别外,为属性访问器定义的所有规则同样适用于索引器访问器。

属性

索引器

允许像调用公共数据成员一样调用方法。

允许对一个对象本身使用数组表示法来访问该对象内部集合中的元素。

可通过简单的名称进行访问。

可通过索引器进行访问。

可以为静态成员或实例成员。

必须为实例成员。

属性的 get 访问器没有参数。

索引器的 get 访问器具有与索引器相同的形参表。

属性的 set 访问器包含隐式 value 参数。

除了值参数外,索引器的 set 访问器还具有与索引器相同的形参表。

支持对使用短语法。

不支持短语法。

五、 索引器示例:

1: using System;

2: using System.Collections.Generic;

3: using System.Linq;

4: using System.Text;

5: using System.Collections.Specialized;

6:

7: namespace CSharp.Indexer

8: {

9: public class Employee

10: {

11: private string _name = "";

12:

13: public string Name

14: {

15: get { return _name; }

16: set { _name = value; }

17: }

18:

19: public Employee(string name)

20: {

21: this._name = name;

22: }

23: }

24:

25: public interface IEmployeeInterface

26: {

27: //int Indexer declaration

28: Employee this[int index]

29: {

30: set;

31: }

32:

33: //string indexer declaration

34: Employee this[string name]

35: {

36: get;

37: set;

38: }

39: }

40:

41: public class EmployeeList : IEmployeeInterface

42: {

43: private ListDictionary empDictionary;

44:

45: public EmployeeList()

46: {

47: empDictionary = new ListDictionary();

48: }

49:

50: // The int indexer.

51: public Employee this[int item]

52: {

53: set

54: {

55: if (value != null && !string.IsNullOrEmpty(value.Name))

56: {

57: empDictionary.Add(value.Name, value);

58: }

59: }

60: }

61:

62: // The string indexer.

63: public Employee this[string name]

64: {

65: get { return (Employee)empDictionary[name]; }

66: set { empDictionary.Add(name, value); }

67: }

68: }

69:

70: class Program

71: {

72: static void Main(string[] args)

73: {

74: EmployeeList empList = new EmployeeList();

75:

76: empList[0] = new Employee("david");

77: empList[1] = new Employee("lisa");

78: empList[2] = new Employee("nana");

79:

80: empList["alice"] = new Employee("alice");

81: empList["sam"] = new Employee("sam");

82:

83: Employee alice = empList["alice"];

84: Console.WriteLine("Alice 's name is {0}", alice.Name);

85: Employee nana = empList["nana"];

86: Console.WriteLine("Nana 's name is {0}", nana.Name);

87:

88: Console.ReadLine();

89: }

90: }

91: }