在循环中声明的变量在循环的每次迭代中都保持值 [英] variable declared within a loop maintains value through each iteration of the loop

查看:80
本文介绍了在循环中声明的变量在循环的每次迭代中都保持值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是错误还是功能,我无法解决

I couldn't work out if this is a bug or a feature

For i = 0 To 4
    Dim strTest As String
    If i = 0 Then
        strTest = "test value"
    End If
    Console.WriteLine(strTest)
Next

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

I thought that by declaring the string inside the loop, it wouldn't maintain its value but after running this code the console has 5 lines of "test value". If instead i declare strTest like:

Dim strTest As String= ""

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

Then the string doesn't maintain its value- which is how i would have expected the function to operate in the first place.

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

Is this intentional behavior by the compiler?

推荐答案

按设计要求破损"

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循环的正文,您将在其中输入一个.循环的迭代.因此,strTest将保留在第一次迭代中设置的值(测试值")用于下一次迭代(1、2、3、4).

The "block" here is the body if the FOR loop, and you are entering it one pr. iteration of the loop. And so strTest will retain the value set in the first iteration ("test value") for the next iterations (1, 2, 3, 4).

这篇关于在循环中声明的变量在循环的每次迭代中都保持值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆