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

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

发布时间:2020-12-17 00:23:05 所属栏目:大数据 来源:网络整理
导读:鉴于下面的代码示例,似乎变量currOn在循环之外被提升并且仅实例化一次.例如,假设itemList中有三个项目,第二次迭代中SomeFunctionThatDoesSomeStuff返回true.那么currOn的值就是真的.在第三次迭代中,我认为给定VB.NET是块范围语言,currOn将被重新实例化并默认
鉴于下面的代码示例,似乎变量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

(编辑:李大同)

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

    推荐文章
      热点阅读