<分区>
表达式 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
的默认值,因此没有相关性。)