可与 foreach 语句一起使用的集合类

博客围绕C#中集合类与foreach的兼容性展开。指出集合类不严格继承IEnumerable和IEnumerator也能与foreach兼容,省略接口可提供类型安全,但会丧失与其他公共语言运行库兼容语言的互操作性,还介绍了同时拥有二者优点的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

foreach 语句是循环访问数组元素的方便方法。如果集合类已实现 System.Collections.IEnumeratorSystem.Collections.IEnumerable 接口,它还可以枚举该集合的元素。
 1None.gif//版权所有 (C) 2000 Microsoft Corporation。保留所有权利。
 2None.gif
 3None.gif// tokens.cs
 4None.gifusing System;
 5None.gif// System.Collections 命名空间已经可用:
 6None.gifusing System.Collections;
 7None.gif
 8None.gif// 声明 Tokens 类:
 9None.gifpublic class Tokens : IEnumerable
10ExpandedBlockStart.gifContractedBlock.gifdot.gif{
11InBlock.gif   private string[] elements;
12InBlock.gif
13InBlock.gif   Tokens(string source, char[] delimiters)
14ExpandedSubBlockStart.gifContractedSubBlock.gif   dot.gif{
15InBlock.gif      // 将字符串分析为标记:
16InBlock.gif      elements = source.Split(delimiters);
17ExpandedSubBlockEnd.gif   }

18InBlock.gif
19InBlock.gif   // IEnumerable 接口实现: 
20InBlock.gif   //  IEnumerable 所需的
21InBlock.gif   //    GetEnumerator() 方法的声明
22InBlock.gif   public IEnumerator GetEnumerator()
23ExpandedSubBlockStart.gifContractedSubBlock.gif   dot.gif{
24InBlock.gif      return new TokenEnumerator(this);
25ExpandedSubBlockEnd.gif   }

26InBlock.gif
27InBlock.gif   // 内部类实现 IEnumerator 接口:
28InBlock.gif   private class TokenEnumerator : IEnumerator
29ExpandedSubBlockStart.gifContractedSubBlock.gif   dot.gif{
30InBlock.gif      private int position = -1;
31InBlock.gif      private Tokens t;
32InBlock.gif
33InBlock.gif      public TokenEnumerator(Tokens t)
34ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
35InBlock.gif         this.t = t;
36ExpandedSubBlockEnd.gif      }

37InBlock.gif
38InBlock.gif      // 声明 IEnumerator 所需的 MoveNext 方法:
39InBlock.gif      public bool MoveNext()
40ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
41InBlock.gif         if (position < t.elements.Length - 1)
42ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
43InBlock.gif            position++;
44InBlock.gif            return true;
45ExpandedSubBlockEnd.gif         }

46InBlock.gif         else
47ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
48InBlock.gif            return false;
49ExpandedSubBlockEnd.gif         }

50ExpandedSubBlockEnd.gif      }

51InBlock.gif
52InBlock.gif      // 声明 IEnumerator 所需的 Reset 方法:
53InBlock.gif      public void Reset()
54ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
55InBlock.gif         position = -1;
56ExpandedSubBlockEnd.gif      }

57InBlock.gif
58InBlock.gif      // 声明 IEnumerator 所需的 Current 属性:
59InBlock.gif      public object Current
60ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
61InBlock.gif         get
62ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
63InBlock.gif            return t.elements[position];
64ExpandedSubBlockEnd.gif         }

65ExpandedSubBlockEnd.gif      }

66ExpandedSubBlockEnd.gif   }

67InBlock.gif
68InBlock.gif   // 测试标记,TokenEnumerator
69InBlock.gif
70InBlock.gif   static void Main()
71ExpandedSubBlockStart.gifContractedSubBlock.gif   dot.gif{
72InBlock.gif      // 通过将字符串分解为标记来测试标记:
73InBlock.gif      Tokens f = new Tokens("This is a well-done program."
74ExpandedSubBlockStart.gifContractedSubBlock.gif         new char[] dot.gif{' ','-'});
75InBlock.gif      foreach (string item in f)
76ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
77InBlock.gif         Console.WriteLine(item);
78ExpandedSubBlockEnd.gif      }

79ExpandedSubBlockEnd.gif   }

80ExpandedBlockEnd.gif}

81None.gif
输出
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 在内部使用一个数组,自行实现 IEnumeratorIEnumerable。该代码示例本可以利用数组本身的枚举方法,但那会使本示例的目的失效。

在 C# 中,集合类并非必须严格从 IEnumerable IEnumerator 继承才能与 foreach 兼容;只要类有所需的 GetEnumeratorMoveNextResetCurrent 成员,便可以与 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# 内的类型安全以及与兼容其他公共语言运行库的语言的互操作性),方法是从 IEnumerableIEnumerator 继承,并使用显式接口实现.

转载于:https://www.cnblogs.com/mazhiyuan/articles/286727.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值