foreach是一個對集合中的元素進行簡單的枚舉及處理的現成語句﹐用法如下﹕
在編譯的時候﹐C#編輯器會對每一個foreach區域進行轉換.
1
using System;
2
using System.Collections;
3
namespace LoopTest
4
{
5
class Class1
6
{
7
static void Main(string[] args)
8
{
9
// create an ArrayList of strings
10
ArrayList array = new ArrayList();
11
array.Add("Marty");
12
array.Add("Bill");
13
array.Add("George");
14
// print the value of every item
15
foreach (string item in array)
16
{
17
Console.WriteLine(item);
18
}
19
}
20
}
21![]()
你可以將foreach語句用在每個實現了Ienumerable接口的集合里﹐如果要了解更多的foreach的用法﹐可查相關SDK.
using System;2
using System.Collections;3
namespace LoopTest4
{5
class Class16
{7
static void Main(string[] args)8
{9
// create an ArrayList of strings10
ArrayList array = new ArrayList();11
array.Add("Marty");12
array.Add("Bill");13
array.Add("George");14
// print the value of every item15
foreach (string item in array)16
{17
Console.WriteLine(item);18
}19
}20
}21

在編譯的時候﹐C#編輯器會對每一個foreach區域進行轉換.
1
IEnumerator enumerator = array.GetEnumerator();
2
try
3
{
4
string item;
5
while (enumerator.MoveNext())
6
{
7
item = (string) enumerator.Current;
8
Console.WriteLine(item);
9
}
10
}
11
finally
12
{
13
IDisposable d = enumerator as IDisposable;
14
if (d != null) d.Dispose();
15
}
16![]()
這說明在后台﹐foreach的管理會給你的程序帶來一些增加系統開銷的額外代碼。
IEnumerator enumerator = array.GetEnumerator();2
try 3
{4
string item;5
while (enumerator.MoveNext()) 6
{7
item = (string) enumerator.Current;8
Console.WriteLine(item);9
}10
}11
finally 12
{13
IDisposable d = enumerator as IDisposable;14
if (d != null) d.Dispose();15
}16





浙公网安备 33010602011771号