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的管理會給你的程序帶來一些增加系統開銷的額外代碼。
|
新聞熱點
疑難解答