VB.NET For 循环函数作用域与块作用域 [英] VB.NET For loop function scope vs block scope
问题描述
鉴于下面的代码示例,变量 currOn
似乎是在循环之外引发的,并且只实例化了一次.例如,假设 itemList
中有三个项目,并且在第二次迭代 SomeFunctionThatDoesSomeStuff
中返回 true
.currOn
的值将是 true
.在第三次迭代中,我会认为给定的 VB.NET 是一种块作用域语言,currOn
将被重新实例化并默认为 false
;但是,我看到它仍然是 true
,因此无论 sOn
的值如何,都不会在进一步的迭代中更新.这似乎是 javascript 的函数范围,其中 currOn
的声明将被拉到循环之外.有人知道这里发生了什么吗?
Given the code sample below, it seems that the variable currOn
is raised up outside of the loop and only instantiated once. For example, say there are three items in itemList
and on the second iteration SomeFunctionThatDoesSomeStuff
returns true
. The value of currOn
will then be true
. On the third iteration, I would have thought that given VB.NET is a block scope language that currOn
would be re-instantiated and default to false
; however, I see that it remains true
and therefore no matter the value of sOn
, does not get updated in further iterations. It seems like javascript's function scope where the declaration of currOn
would be pulled up outside the loop. Anyone know what's going on here?
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
每次迭代似乎都像我预期的那样工作.
As a further example, explicitly setting currOn = false
every iteration seems to work as I would have expected the above to work.
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
循环中声明变量时,您就是在块范围内声明它.在块内声明的对象只能在该块内访问,但在整个过程中都有生命周期.
When declaring a variable within a For
loop you are declaring it within a block scope. The objects that have been declared within a block will only be accessible within that block but will have a lifetime across the entire procedure.
来自 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
这篇关于VB.NET For 循环函数作用域与块作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!