为什么Convert.ToString(NULL)返回,如果你施放空不同的值? [英] Why does Convert.ToString(null) return a different value if you cast null?
问题描述
Convert.ToString(null)
返回
null
正如我所料。
As I expected.
但
Convert.ToString(null as object)
返回
""
为什么这些不同?
Why are these different?
推荐答案
有2重载的ToString
的这里都有了用武之地
There are 2 overloads of ToString
that come into play here
Convert.ToString(object o);
Convert.ToString(string s);
C#编译器实质上是尝试挑选最具体的超负荷工作,并会与输入。 A 空
值转换为任何引用类型。在这种情况下字符串
比对象
,因此它将被选为优胜者更具体。
The C# compiler essentially tries to pick the most specific overload which will work with the input. A null
value is convertible to any reference type. In this case string
is more specific than object
and hence it will be picked as the winner.
在 null作为对象
您已经凝固的EX pression类型为对象
。这意味着它不再与字符串兼容
过载和编译器采对象
超载,因为它是唯一兼容的一个剩余。
In the null as object
you've solidified the type of the expression as object
. This means it's no longer compatible with the string
overload and the compiler picks the object
overload as it's the only compatible one remaining.
这是如何打破平局的作品涵盖了C#语言规范第7.4.3真的毛茸茸的细节。
The really hairy details of how this tie breaking works is covered in section 7.4.3 of the C# language spec.
这篇关于为什么Convert.ToString(NULL)返回,如果你施放空不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!