加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

对于条件VB.NET vs C#

发布时间:2020-12-17 00:07:07 所属栏目:大数据 来源:网络整理
导读: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#:
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 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 …循环,它可以在循环开始或结束时运行While或Until条件.使用该语句,每个循环都会评估循环条件.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读