C#:
static class Module1 { public static void Main() { for (index = 1; index <= GetCount(); index++) { Console.WriteLine("For {0}",index); } Console.ReadKey(); } public static int GetCount() { Console.WriteLine("GetCount"); return 10; } }
结果(C#重新检查条件):
GetCount For 1 GetCount For 2 GetCount For 3 GetCount For 4 GetCount For 5 GetCount For 6 GetCount For 7 GetCount For 8 GetCount For 9 GetCount For 10 GetCount
VB.NET
Module Module1 Sub Main() For index = 1 To GetCount() Console.WriteLine("For {0}",index) Next Console.ReadKey() End Sub Public Function GetCount() As Integer Console.WriteLine("GetCount") Return 10 End Function End Module
结果(VB.NET不重新检查条件):
GetCount For 1 For 2 For 3 For 4 For 5 For 6 For 7 For 8 For 9 For 10
a)为什么VB.NET不遵守每次重复的“条件”的“规则”?
b)有没有办法强制VB重新检查这种情况?
C#和VB.NET是不同的语言,类似的关键字可以有不同的语义.
从the docs for For ... Next
(我的重点):
When a
For...Next
loop starts,Visual Basic evaluatesstart
,end
,andstep
. This is the only time it evaluates these values.
从C#规范的第8.8.3节(同上):
When and if control reaches the end point of the embedded statement (possibly from execution of a continue statement),the expressions of the for-iterator,if any,are evaluated in sequence,and then another iteration is performed,starting with evaluation of the for-condition in the step above.
如果你想强制每次检查条件,VB.NET提供极其灵活的Do …循环,它可以在循环开始或结束时运行While或Until条件.使用该语句,每个循环都会评估循环条件.