foreach是一個(gè)對(duì)集合中的元素進(jìn)行簡(jiǎn)單的枚舉及處理的現(xiàn)成語(yǔ)句,用法如下例所示:
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語(yǔ)句用在每個(gè)實(shí)現(xiàn)了Ienumerable接口的集合里。如果想了解更多foreach的用法,你可以查看.NET Framework SDK文檔中的C# Language Specification。
在編譯的時(shí)候,C#編輯器會(huì)對(duì)每一個(gè)foreach 區(qū)域進(jìn)行轉(zhuǎn)換。
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();
}
這說(shuō)明在后臺(tái),foreach的管理會(huì)給你的程序帶來(lái)一些增加系統(tǒng)開(kāi)銷的額外代碼。
新聞熱點(diǎn)
疑難解答