c# - 声明变量并使用 TryParse 在同一行对其进行初始化有任何问题吗?

标签 c# initialization declaration

这个示例是用 C# 编写的,但我希望可以同样轻松地应用于其他示例。

我最近发现以下似乎工作得很好:

int i = Int32.TryParse(SomeString, out i) ? i : -1;

不知何故,似乎变量 i 在它出现在 TryParse 中时在技术上不应该是可访问的。或者我假设 int i 有效地声明了变量是否正确,即使还没有语句结束?

最佳答案

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
        }
    }
}

关于c# - 声明变量并使用 TryParse 在同一行对其进行初始化有任何问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4566205/

相关文章:

node.js - 在 node.js 中将模块导入为 const 和 var 的区别

c - extern 和 static 的正确用法是什么?

c# - 比较网站的文本内容

arrays - 在 C 错误 "expected expression before ‘]’ token 中初始化数组”

c++ - 列表初始化(使用花括号)有什么好处?

mysql - 在 MySQL 初始化后立即执行 SQL 语句的最佳实践是什么?

variables - 此处不允许变量声明

c# - .NET 非/通用列表存储在堆栈还是堆上?

c# - 带服务和控制台的 System.Threading.Mutex

c# - 是什么让表单成为根引用?