有关foreach的小研究

来源:互联网 发布:淘宝大号刷多少单危险 编辑:程序博客网 时间:2024/05/01 04:50

因为以前接触的是java再以前是c所以一直没有机会看到foreach这个东西,现在看到了正好研究研究。

foreach是一个对集合中的元素进行简单的枚举及处理的现成语句,用法如下例所示:

using System;using System.Collections;namespace LoopTest{class Class1{   static void Main(string[] args)   {      // create an ArrayList of strings      ArrayList array = new ArrayList();      array.Add("Marty");      array.Add("Bill");      array.Add("George");      // print the value of every item      foreach (string item in array)      {         Console.WriteLine(item);      }   }}

可以将foreach语句用在每个实现了Ienumerable接口的集合里。如果想了解更多foreach的用法,可以查看.NET Framework SDK文档中的C# Language Specification。

在编译的时候,C#编辑器会对每一个foreach 区域进行转换。

IEnumerator enumerator = array.GetEnumerator();try {   string item;   while (enumerator.MoveNext())    {      item = (string) enumerator.Current;      Console.WriteLine(item);   }}finally {   IDisposable d = enumerator as IDisposable;   if (d != null) d.Dispose();}

这说明在后台,foreach的管理会给你的程序带来一些增加系统开销的额外代码。

但是换个角度,不用foreach的话也会引入一些局部变量做步进器,各有千秋吧。