gpt4 book ai didi

c# - 对于条件 VB.NET 与 C#

转载 作者:可可西里 更新时间:2023-11-01 03:08:56 25 4
gpt4 key购买 nike

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 不遵守在每次迭代时重新检查 For 条件的“规则”?
b) 是否有办法强制 VB 重新检查此条件?

最佳答案

C#和VB.NET是不同的语言,相似的关键字可以有不同的语义。

来自 the docs for For ... Next (我的重点):

When a For...Next loop starts, Visual Basic evaluates start, end, and step. 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 ... Loop,它可以有一个 While 一个 Until 条件,在开始时运行循环结束。使用该语句,循环条件每次都评估。

关于c# - 对于条件 VB.NET 与 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5965508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com