我一直有这样的印象:在 VB.NET 中声明变量会自动将该变量设置为其数据类型的默认值(与 C# 不同)。
所以,之后
Dim intValue As Integer intValue是 0Dim dateValue As Date dateValue是 1/1/0001Dim stringValue As String stringValue是NothingDim strValue As Point strValue是 (0; 0)等等。
但现在我在循环内声明了一个变量,并且令我惊讶的是,尽管重复声明,但该变量仍保留其值。所以,
For index As Integer = 1 To 10
Dim test As Integer
test += 1
Console.WriteLine(test)
Next index
Run Code Online (Sandbox Code Playgroud)
输出从 1 到 10 的数字,并且不输出数字 1 的十倍。
有人可以解释一下为什么吗?这是一个错误还是应该像这样工作?
文档说:
Visual Basic 每次运行该
Dim语句时都会将指定的值分配给变量。如果不指定初始值,Visual Basic 将在第一次输入包含该语句的代码时Dim为变量的数据类型分配默认初始值。