声明变量并使用TryParse在同一行初始化它的任何问题?

JYe*_*ton 17 c# initialization declaration

这个例子是在C#中,但我希望可以轻松地应用于其他人.

我最近发现以下似乎工作正常:

int i = Int32.TryParse(SomeString, out i) ? i : -1;
Run Code Online (Sandbox Code Playgroud)

不知怎的,似乎变量i在技​​术上不应该在它出现的时候可访问TryParse.或者我是否正确地假设int i有效地声明变量,即使声明还没有结束呢?

Jef*_*tin 10

int i声明变量,并在out参数中使用它初始化它.由于谓词必须在结果之前进行评估,i因此在使用之前都要声明和初始化.(out必须在返回之前分配参数,因此无论如何都必须初始化.)

也就是说,我的同事们会在风格上看到类似的东西.:-)

编辑:在调查了这是如何动摇之后,我将提出一些可能的替代辅助方法.静态类的命名在此处充当辅助方法的意图文档.

internal static class TryConvert
{
    /// <summary>
    /// Returns the integer result of parsing a string, or null.
    /// </summary>
    internal static int? ToNullableInt32(string toParse)
    {
        int result;
        if (Int32.TryParse(toParse, out result)) return result;
        return null;
    }

    /// <summary>
    /// Returns the integer result of parsing a string,
    /// or the supplied failure value if the parse fails.
    /// </summary>
    internal static int ToInt32(string toParse, int toReturnOnFailure)
    {
        // The nullable-result method sets up for a coalesce operator.
        return ToNullableInt32(toParse) ?? toReturnOnFailure;
    }
}

internal static class CallingCode
{
    internal static void Example(string someString)
    {
        // Name your poison. :-)
        int i = TryConvert.ToInt32(someString, -1);
        int j = TryConvert.ToNullableInt32(someString) ?? -1;

        // This avoids the issue of a sentinel value.
        int? k = TryConvert.ToNullableInt32(someString);
        if (k.HasValue)
        {
            // do something
        }
    }
}
Run Code Online (Sandbox Code Playgroud)