
2

3

4

5

6

7

8

9

10



11

12

13

14



15

16

17

18

19

20

21

22

23



24

25

26

27

28

29



30

31

32

33

34



35

36

37

38

39

40



41

42



43

44

45

46

47



48

49

50

51

52

53

54



55

56

57

58

59

60



61

62



63

64

65

66

67

68

69

70

71



72

73

74



75

76



77

78

79

80

81

输出
This is a well done program.
代码讨论
在前面的示例中,下列代码用于 Tokens
化,方法是将“This is a well-done program.”拆分为标记(使用“”和“-”作为分隔符),并用 foreach 语句枚举这些标记:
Tokens f = new Tokens("This is a well-done program.", new char[] {' ','-'}); foreach (string item in f) { Console.WriteLine(item); }
请注意,Tokens
在内部使用一个数组,自行实现 IEnumerator
和 IEnumerable
。该代码示例本可以利用数组本身的枚举方法,但那会使本示例的目的失效。
在 C# 中,集合类并非必须严格从 IEnumerable 和 IEnumerator 继承才能与 foreach 兼容;只要类有所需的 GetEnumerator
、MoveNext
、Reset
和 Current
成员,便可以与 foreach 一起使用。省略接口的好处为,使您可以将 Current
的返回类型定义得比 object 更明确,从而提供了类型安全。
例如,从上面的示例代码开始,更改以下几行:
public class Tokens // no longer inherits from IEnumerable public TokenEnumerator GetEnumerator() // doesn't return an IEnumerator public class TokenEnumerator // no longer inherits from IEnumerator public string Current // type-safe: returns string, not object
现在,由于 Current
返回字符串,当 foreach 语句中使用了不兼容的类型时,编译器便能够检测到:
foreach (int item in f) // Error: cannot convert string to int
省略 IEnumerable 和 IEnumerator 的缺点是,集合类不再能够与其他公共语言运行库兼容的语言的 foreach 语句(或等效项)交互操作。
您可以同时拥有二者的优点(C# 内的类型安全以及与兼容其他公共语言运行库的语言的互操作性),方法是从 IEnumerable 和 IEnumerator 继承,并使用显式接口实现.