C# String.Empty 与 Null 上的 Convert.ToInt32(String)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14840889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:12:03  来源:igfitidea点击:

Convert.ToInt32(String) on String.Empty vs. Null

c#.nettype-conversion

提问by MCattle

The expression Convert.ToInt32(String.Empty)will raise a FormatException because it cannot parse an empty string into an Int32 value.

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

However, the expression Convert.ToInt32(DirectCast(Nothing, String))in VB.NET or Convert.ToInt32((string)null)in C# will parse the null to an Int32 value of zero.

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

Digging into the .NET source in Convert.cs, I see the following code:

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

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

This explains the behaviour, but I'd like to understand why it was written this way, instead of returning a zero for an empty string as well?

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

For example, why wasn't it written as:

例如,为什么不写为:

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

(Note that String.IsNullOrEmpty()and Convert.ToInt32()both date back to .NET 2.0, possibly earlier.)

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

Edit:My question is very similar to this question, but I'd also like to know why Convert.ToInt32(String.Empty)raises an exception instead of returning the Int32 default value of 0. (The answer being that String.Emptyis not the default value of String, so there's no correlation.)

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

采纳答案by Honza Brestan

I have absolutely no insight into the actual design team's reasoning behind this, but it seems to me that it might be some sort of "default value equivalency". Null is the default value of string, so it seems logical to convert it to a default value of int. String.Empty is however a string like any other non-null string data, so it is expected to be formatted, hence the exception.

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

I think ArgumentNullException would have been a "cleaner" decision, but I don't know whatever internal issues may be behind this all...

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

Another edit:
There, right in the MSDN documentation, one of the 5 possible outcomes:

另一个编辑:
MSDN 文档中,有 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 succeedand the method will return a value of the targeted base type.

一次成功的转换。对于之前结果中未列出的两种不同基类型之间的转换,所有不会导致数据丢失的扩大转换以及所有缩小转换都将成功,并且该方法将返回目标基类型的值。

It seems the conversion from null object to another type has no reason to fail (not a format error, not an unsupported typeconversion), but a value type such as int has no representation of "no data", so a default value of the target type is produced.

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

A quick thought - the "opposite" conversion, Convert.ToString(0), does not yield null because:

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

  • 0 is data, it can be very valid and important value in many cases
  • null is not a correct string representation of 0
  • 0 是数据,在很多情况下它可以是非常有效和重要的值
  • null 不是 0 的正确字符串表示