【问题标题】:Using unassigned value explanation. Unexpected behavior使用未赋值的解释。意外行为
【发布时间】:2020-06-05 10:18:28
【问题描述】:
        public static void Main()
    {
        int n;
        //n++;    Of course it would cause 'Use of unassigned local variable error' compiler error.
        int.TryParse("not an int", out n);    //not assignig here
        n++;   //now legal. Why?
        System.Console.WriteLine(n);   //1
    }

我不明白为什么这段代码会这样。一开始它不允许使用未分配的变量,但在 TryParse 之后它允许使用,尽管 TryParse 没有为变量分配任何东西。在某些时候变量被分配给默认值 0(我想从一开始)但是这种行为的逻辑和解释是什么?

【问题讨论】:

  • 你知道什么时候方法有out参数然后它必须分配一些东西吗? ...所以在 SomeMethod(out n) - n 总是被分配之后......并且 TryParse 不给变量分配任何东西 不是真的
  • out 参数修饰符。

标签: c# variable-assignment theory


【解决方案1】:

反编译C#int.TryParse定义:

public static bool TryParse(string s, out int result)
{
    return Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}


// System.Number
internal unsafe static bool TryParseInt32(string s, NumberStyles style, NumberFormatInfo info, out int result)
{
    byte* stackBuffer = stackalloc byte[1 * 114 / 1];
    Number.NumberBuffer numberBuffer = new Number.NumberBuffer(stackBuffer);
    result = 0;
    if (!Number.TryStringToNumber(s, style, ref numberBuffer, info, false))
    {
        return false;
    }
    if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
    {
        if (!Number.HexNumberToInt32(ref numberBuffer, ref result))
        {
            return false;
        }
    }
    else
    {
        if (!Number.NumberToInt32(ref numberBuffer, ref result))
        {
            return false;
        }
    }
    return true;
}

如您所见,result 设置为0,这是因为"not an int" 实际上是...而不是int。如果转换尝试失败(如果您想这样看),此函数会将结果设置为0

【讨论】:

    【解决方案2】:

    this other question 中所述,局部变量未初始化。

    根据Microsoft Docs

    当此方法返回时,如果转换成功,[result] 包含与 s[entry string] 中包含的数字等效的 32 位有符号整数值,如果转换失败,则返回零。

    所以在 tryparse 之后,n 被初始化为值 0。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-05
      • 1970-01-01
      相关资源
      最近更新 更多