c# - Convert.ToInt32(String) on String.Empty 与 Null

标签 c# .net type-conversion

<分区>

表达式 Convert.ToInt32(String.Empty) 将引发 FormatException,因为它无法将空字符串解析为 Int32 值。

但是,VB.NET 中的表达式 Convert.ToInt32(DirectCast(Nothing, String)) 或 C# 中的 Convert.ToInt32((string)null) 将解析将 null 转换为零的 Int32 值。

深入研究 Convert.cs 中的 .NET 源代码,我看到以下代码:

public static int ToInt32(String value) {
    if (value == null) 
        return 0;
    return Int32.Parse(value, CultureInfo.CurrentCulture);
}

这解释了行为,但我想了解为什么它是这样写的,而不是为空字符串也返回零?

比如为什么不写成:

public static int ToInt32(String value) {
    if (String.IsNullOrEmpty(value)) 
        return 0;
    return Int32.Parse(value, CultureInfo.CurrentCulture);
}

(请注意,String.IsNullOrEmpty()Convert.ToInt32() 都可以追溯到 .NET 2.0,可能更早。)

编辑: 我的问题与 this question 非常相似,但我也想知道为什么 Convert.ToInt32(String.Empty) 引发异常而不是返回 Int32 默认值 0。 (答案是 String.Empty 不是 String 的默认值,因此没有相关性。)

最佳答案

我完全不了解实际设计团队背后的推理,但在我看来,这可能是某种“默认值等效”。 null 是 string 的默认值,因此将其转换为 int 的默认值似乎是合乎逻辑的。然而,String.Empty 是一个类似于任何其他非空字符串数据的字符串,因此它应该被格式化,因此是异常。

我认为 ArgumentNullException 会是一个“更干净”的决定,但我不知道这一切背后可能有什么内部问题......

另一个编辑:
那里,就在 MSDN documentation ,5 种可能结果之一:

A successful conversion. For conversions between two different base types not listed in the previous outcomes, all widening conversions as well as all narrowing conversions that do not result in a loss of data will succeed and the method will return a value of the targeted base type.

似乎从空对象到另一种类型的转换没有理由失败(不是格式错误,不是不支持的类型转换),但是值类型如int没有表示“无数据”,因此生成目标类型的默认值。

快速思考 - “相反”转换 Convert.ToString(0) 不会产生 null,因为:

  • 0是数据,在很多情况下它可以是非常有效和重要的值
  • null 不是 0 的正确字符串表示

关于c# - Convert.ToInt32(String) on String.Empty 与 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14840889/

相关文章:

c# - 我想将电子邮件发送到本地网络中的某个 ID

c# - 为什么我可以将 sbyte 与所有其他数字类型*except* ulong 进行比较?

python - 修改Python脚本批量转换目录下所有 "WOFF"文件

c# - 我如何在 C# 中将数据从字符串转换为长

c# - Convert.ChangeType 生成具体类型元素数组,而不是对象

c# - 如何从 4 个复选框中选中任意 2 个复选框?

c# - 检测 Windows 7 审核模式

c# - 在 C# 字符串中通过 HTML 搜索特定文本并标记文本的最佳方法是什么?

c# - 套接字连接在我读取数据之前重置

c# - Visual C# - 我应该为这个任务使用什么样的表单控件?