c# - 变量在循环中保留其值?

标签 c# .net vb.net

如果我在控制台应用程序中运行这个简单的代码:

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/

相关文章:

c# - 在 C# 中相当于 Ruby "redo"

.net - ZedGraph 库的开发仍然活跃吗?如果没有 - 有任何开源替代品吗?

c# - VB.Net Power 运算符 (^) 从 C# 重载

c# - 遍历 ICollection 并设置为 null

c# - 如何创建多语言网站

c# - 自定义日期时间格式

vb.net - 故意在VB.NET中导致程序崩溃

.Net - 对一组数值求和的最快方法

.net - 如何控制 winforms 属性网格中 ExpandableObject 属性的顺序?

mysql - 与 MySql 中的数据库的 Visual Basic 连接