现在的位置: 首页 > 综合 > 正文

如何讓Foreach循環運行的更快

2012年05月02日 ⁄ 综合 ⁄ 共 798字 ⁄ 字号 评论关闭
foreach是一個對集合中的元素進行簡單的枚舉及處理的現成語句﹐用法如下﹕
 1using System;
 2using System.Collections;
 3namespace LoopTest
 4{
 5class Class1
 6{
 7static void Main(string[] args)
 8{
 9// create an ArrayList of strings
10ArrayList array = new ArrayList();
11array.Add("Marty");
12array.Add("Bill");
13array.Add("George");
14// print the value of every item
15foreach (string item in array)
16{
17Console.WriteLine(item);
18}

19}

20}

21

你可以將foreach語句用在每個實現了Ienumerable接口的集合里﹐如果要了解更多的foreach的用法﹐可查相關SDK.
在編譯的時候﹐C#編輯器會對每一個foreach區域進行轉換.

 1IEnumerator enumerator = array.GetEnumerator();
 2try 
 3{
 4string item;
 5while (enumerator.MoveNext()) 
 6{
 7item = (string) enumerator.Current;
 8Console.WriteLine(item);
 9}

10}

11finally 
12{
13IDisposable d = enumerator as IDisposable;
14if (d != null) d.Dispose();
15}

16

這說明在后台﹐foreach的管理會給你的程序帶來一些增加系統開銷的額外代碼。

抱歉!评论已关闭.