【发布时间】:2021-12-22 00:48:35
【问题描述】:
我在使用 vb.net(框架 4.8、VS2019、Option Explicit 和 StrictOn)和 For Each 循环内的字符串变量时遇到了一个奇怪的行为。
为什么tmpVal 变量没有在每个循环中重新初始化,或者我可能遗漏了什么?
这是我的代码:
Sub Main()
Dim Props() As String = {"one", "two", "three"}
For Each cProp As String In Props
Dim tmpVal As String
If cProp = "two" Then
If String.IsNullOrEmpty(tmpVal) Then
tmpVal = cProp
Else
tmpVal = "Nope"
End If
End If
Console.WriteLine("cProp " & cProp & " : " & tmpVal)
Next
Console.ReadKey()
End Sub
我得到的输出:
cProp one :
cProp two : two
cProp three : two
我原以为第三行是“空的”
谢谢
【问题讨论】:
-
当
cProp = "two" And String.IsNullOrEmpty(tmpVal)时,您只分配一次tempVal。否则永远不会更新。
标签: vb.net foreach local-variables .net-framework-4.8