循环语句
foreach 语句的本质
foreach是一个语法糖。
http://www.cnblogs.com/1-2-3/archive/2008/03/10/net-basic-knowledge-3-cs-vb-for-while-statement.html
| C# | VB | 输出 |
|---|---|---|
| int i = 0; while (i <= 2) { Console.WriteLine(i); i++; }; // 这个分号可有可无 | Dim i As Integer = 0 While i <= 2 Console.WriteLine(i) i += 1 End While | 0 1 2 |
| int i = 0; do { Console.WriteLine(i); i++; } while (i <= 2); // 这个分号必须写 | Dim i As Integer = 0 Do Console.WriteLine(i) i += 1 Loop While i <= 2 | 0 1 2 |
| / | Dim i As Integer = 0 Do Console.WriteLine(i) i += 1 Loop Until i >= 3 | 0 1 2 |
| / | Dim i As Integer = 0 Do While i <= 2 Console.WriteLine(i) i += 1 Loop | 0 1 2 |
| / | Dim i As Integer = 0 Do Until i >= 3 Console.WriteLine(i) i += 1 Loop | 0 1 2 |
| / | Do Console.WriteLine("Hello") Loop | Hello Hello Hello ……无限循环 |
| for (; ; ) { Console.WriteLine("Hello"); } | / | Hello Hello Hello ……无限循环 |
| for (int i = 2; i >= 0; i--) { Console.WriteLine(i); }; // 这个分号可有可无 | For i As Integer = 2 To 0 Step -1 Console.WriteLine(i) Next | 2 1 0 |
| int i = 0; do { for (int j = 1; j <= 10; j++) { Console.WriteLine(i.ToString() + j.ToString()); if (j >= 2) { break; } if (i >= 3) { goto enddo; } } i++; } while (true); enddo: ; | Dim i As Integer = 0 Do For j As Integer = 1 To 10 Console.WriteLine(i & j) If j >= 2 Then Exit For End If If i >= 3 Then Exit Do End If Next i += 1 Loop | 01 02 11 12 21 22 31 |
| for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { continue; } Console.WriteLine(i); } | For i As Integer = 1 To 10 If (i Mod 2 = 0) Then Continue For End If Console.WriteLine(i) Next | 1 3 5 7 9 |
| int[] a = new int[] { 2, 4, 6 }; foreach (int i in a) { Console.WriteLine(i); } | Dim a() As Integer = New Integer() {2, 4, 6} For Each i As Integer In a Console.WriteLine(i) Next | 2 4 6 |
foreach 语句的本质
foreach是一个语法糖。
IList
<
int
>
a
=
new
List
<
int
>
();
foreach ( int i in a)
{
Console.WriteLine(i);
}
会被编译器转换成
foreach ( int i in a)
{
Console.WriteLine(i);
}
IList
<
int
>
a
=
new
List
<
int
>
();
IEnumerator < int > e = a.GetEnumerator();
try
{
while (e.MoveNext())
{
Console.WriteLine(e.Current);
}
}
finally
{
if (e != null )
e.Dispose();
}
IEnumerator < int > e = a.GetEnumerator();
try
{
while (e.MoveNext())
{
Console.WriteLine(e.Current);
}
}
finally
{
if (e != null )
e.Dispose();
}
http://www.cnblogs.com/1-2-3/archive/2008/03/10/net-basic-knowledge-3-cs-vb-for-while-statement.html
本文详细解析了C#与VB中的多种循环语句用法,包括while、do...while、for及foreach等,并提供了丰富的代码示例,帮助读者深入理解不同循环结构的特点及其应用场景。
2079

被折叠的 条评论
为什么被折叠?



