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

.net – 在循环中声明的变量通过循环的每次迭代维护值

发布时间:2020-12-17 00:19:47 所属栏目:大数据 来源:网络整理
导读:如果这是一个错误或功能,我无法解决 For i = 0 To 4 Dim strTest As String If i = 0 Then strTest = "test value" End If Console.WriteLine(strTest)Next 我认为通过在循环中声明字符串,它不会保持其值,但在运行此代码后,控制台有5行“测试值”.如果相反我
如果这是一个错误或功能,我无法解决
For i = 0 To 4
    Dim strTest As String
    If i = 0 Then
        strTest = "test value"
    End If
    Console.WriteLine(strTest)
Next

我认为通过在循环中声明字符串,它不会保持其值,但在运行此代码后,控制台有5行“测试值”.如果相反我声明strTest像:

Dim strTest As String= ""

然后字符串不会保持其值 – 这就是我期望函数首先运行的方式.

这是编译器的故意行为吗?

“按设计破碎”

http://msdn.microsoft.com/en-us/library/1t0wsc67.aspx

Note 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.

这里的“块”是FOR循环的主体,而你输入的是一个pr.循环的迭代.因此strTest将保留第一次迭代中设置的值(“测试值”)以用于下一次迭代(1,2,3,4).

(编辑:李大同)

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

    推荐文章
      热点阅读