【问题标题】:Local String-variable initialization in Loop循环中的局部字符串变量初始化
【发布时间】:2021-12-22 00:48:35
【问题描述】:

我在使用 vb.net(框架 4.8、VS2019、Option ExplicitStrictOn)和 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


【解决方案1】:

在循环中声明一个变量并不意味着它会在每次迭代时被初始化。
它只是将范围限制在循环中。

意味着它将在您的示例中初始化一次为Nothing

您可以按如下方式更改初始化以获得预期的结果:

Dim tmpVal As String = ""

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-03-17
  • 2016-09-07
  • 2012-10-03
  • 2011-05-24
  • 1970-01-01
  • 2014-05-01
  • 2017-05-14
  • 2016-01-14
相关资源
最近更新 更多