如果这是一个错误或功能,我无法解决
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= ""
然后字符串不会保持其值 – 这就是我期望函数首先运行的方式.
这是编译器的故意行为吗?
“按设计破碎”
原文链接:https://www.f2er.com/vb/255361.htmlhttp://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).