代码之家  ›  专栏  ›  技术社区  ›  Andreas Brinck

不更新out变量的正确方法是什么

c#
  •  3
  • Andreas Brinck  · 技术社区  · 14 年前

    我已经实现了 TryParse 类的函数 MinMax 这样地:

        public static bool TryParse(string s, out MinMax result)
        {
            var parts = s.Split(' ');
            if (parts.Length != 2)
            {
                return false;
            }
            float min;
            float max;
            if (!float.TryParse(parts[0].Trim(), out min) || !float.TryParse(parts[1].Trim(), out max))
            {
                return false;
            }
            result = new MinMax(min, max);
            return true;
        }
    

    但是,这并不能编译,因为显然需要编写out参数。解决这个问题的正确方法是什么?我希望能够使用该函数,以便在解析失败时,传递给它的参数保持不变。我想一种方法是添加如下内容:

    result = result;
    

    但这条线发出了警告。

    6 回复  |  直到 14 年前
        1
  •  2
  •   Gerrie Schenck    14 年前

    假设MinMax是一个引用类型,只需将null赋给它。就像其他的胰蛋白酶方法一样。

    查看此代码:

        string s = "12dfsq3";
        int i = 444;
        int.TryParse(s, out i);
        Console.WriteLine(i);
    

    我将被设置为0而不是保持在444。

        2
  •  3
  •   Mitch Wheat    14 年前

    通过参考:

    public static bool TryParse(string s, ref MinMax result) 
    

    这意味着你必须确保 result 参数已初始化。

    更新:最好遵循 TryParse . (我有时会因为回答了真正的问题而受到批评,而不是被问到的问题!)!这一次正好相反!)

        3
  •  2
  •   mjfgates    14 年前

    鉴于out参数甚至不需要由调用者初始化,您真的需要对它做些什么。

    您可以使用ref参数代替,这些参数不需要您在函数中触摸它们。

        4
  •  1
  •   batwad    14 年前

    我不喜欢这些答案告诉你用 ref 参数,因为它会更改方法的语义,并要求调用方传递初始化的值。

    result 到的默认值 MinMax ,这是 null 如果是引用类型,或者使用 default 接线员。

    result = default(MinMax);
    
        5
  •  1
  •   Henrik    14 年前

    不更新out变量的唯一正确方法是抛出异常。改变 out ref .

        6
  •  0
  •   LukeH    14 年前

    你必须设置 out 变量。你可以用 ref 正如其他答案所暗示的,但我不建议这样做——标准不是这样的 TryParse 模式应该有效。再说了,又丑又没必要。

    什么都不重要 result 包含在失败案例中,因为 bool 返回的值指示解析是否成功。回来吧 new MinMax(0, 0) 或者,如果你愿意, default(MinMax) :

    public static bool TryParse(string s, out MinMax result)
    {
        string[] parts = s.Split(' ');
        if (parts.Length == 2)
        {
            float min, max;
            if (float.TryParse(parts[0].Trim(), out min)
                    && float.TryParse(parts[1].Trim(), out max))
            {
                result = new MinMax(min, max);
                return true;
            }
        }
    
        result = default(MinMax);    // or just use "result = new MinMax(0, 0);"
        return false;
    }