.net 基础知识大杂烩(3) ——循环语句

本文详细解析了C#与VB中的多种循环语句用法,包括while、do...while、for及foreach等,并提供了丰富的代码示例,帮助读者深入理解不同循环结构的特点及其应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

循环语句

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);
}
会被编译器转换成
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();
}

http://www.cnblogs.com/1-2-3/archive/2008/03/10/net-basic-knowledge-3-cs-vb-for-while-statement.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值