如果我在控制台应用程序中运行这个简单的代码:
For i As Integer = 1 To 10
Dim s As String = i.ToString()
Dim x As Decimal
If i = 1 Then
x = Decimal.Parse(s)
End If
Console.WriteLine(x.ToString())
Next
Console.ReadLine()
出乎意料的是,x
保留其值 1,因此 1 被打印了 10 次。我认为循环的每次迭代都是它自己的代码块,并且状态没有延续?为什么会出现这种情况?我希望 x
具有默认值 System.Decimal
。
在 C# 中也会发生同样的情况,只是编译器不允许您对未初始化的变量调用 ToString()
,但如果您在 Visual Studio 中设置断点,您可以看到 x
保留其值 1。
for (int i = 1; i <= 10; i++)
{
string s = i.ToString();
Decimal x;
if(i == 1)
{
x = Decimal.Parse(s);
}
// Value of x remains 1
}
Console.ReadLine();
最佳答案
关于 VB.NET,请查看范围 here 。在“ block 范围”部分中,有一条注释说明了以下内容:
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.
因此,这种行为是设计使然,您应该将变量初始化为代码需要的任何值。
我修改了您的代码,以显示第一次 x 初始化为 0,但之后它保留值 1。
For i As Integer = 1 To 10
Dim s As String = i.ToString()
Dim x As Decimal
Console.WriteLine(x.ToString())
If i = 1 Then
x = Decimal.Parse(s)
End If
Console.WriteLine(x.ToString())
Next
Console.ReadLine()
关于c# - 变量在循环中保留其值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70454895/