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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/vb/255297.html

猜你在找的VB相关文章