微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

VB.NET用于循环函数范围与块范围

鉴于下面的代码示例,似乎变量currOn在循环之外被提升并且仅实例化一次.例如,假设itemList中有三个项目,第二次迭代中SomeFunctionThatDoesSomeStuff返回true.那么currOn的值就是真的.在第三次迭代中,我认为给定VB.NET是块范围语言,currOn将被重新实例化并认为false;但是,我发现它仍然是正确的,因此无论sOn的值如何,都不会在进一步的迭代中得到更新.它似乎是 javascript函数范围,其中currOn的声明将在循环外被拉出.有谁知道这里发生了什么?
For Each item As MyItem In itemList
            Dim currOn As Boolean
            Dim sOn As Boolean = SomeFunctionThatDoesstuff(item)
            currOn = currOn OrElse sOn

            Debug.Print(String.Format("the value of currOn is: {0}",currOn))
        Next

作为另一个例子,显式设置currOn = false每次迭代似乎都可以正常工作,因为我预期上述工作.

For Each item As MyItem In itemList

                Dim currOn As Boolean = False
                Dim sOn As Boolean = SomeFunctionThatDoesstuff()
                currOn = currOn OrElse sOn

                Debug.Print(String.Format("the value of currOn is: {0}",currOn))
            Next
在For循环中声明变量时,您将在块范围内声明它.已在块中声明的对象只能在该块中访问,但在整个过程中将具有生命周期.

来自MSDN:

Even if the scope of a variable is limited to a block,its lifetime is still that of the entire procedure. If you enter the block more than once during the procedure,each block variable retains its prevIoUs value. To avoid unexpected results in such a case,it is wise to initialize block variables at the beginning of the block.

MSDN链接https://msdn.microsoft.com/en-us/library/1t0wsc67.aspx

原文地址:https://www.jb51.cc/vb/255297.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐