什么时候null不是null

什么时候null不是null

本文介绍了什么时候null不是null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





想知道是否有人可以解释这个:



以下返回null。



Hi,

Was wondering if someone can explain this:

The following returns null.

Convert.ToString(null)





以下返回null。





The following returns null.

Request.QueryString["InvalidQSParamName"]





但是以下内容返回一个空字符串。





But the following returns an empty string.

Convert.ToString(Request.QueryString["InvalidQSParamName"])





as





As does

string myString = Request.QueryString["InvalidQSParamName"];
Convert.ToString(myString)





但这会返回null





But this returns null

string myString = null;
Convert.ToString(myString)







任何人都可以解释为什么行为差异两个?




Can anyone explain why the difference in behaviour between two?

推荐答案


引用:

返回值

类型:System.String

字符串表示值为null,如果value为null,则为String.Empty。

Return Value
Type: System.String
The string representation of value, or String.Empty if value is null.





和 []





And MSDN Convert.ToString(string)[^]

引用:

返回值

类型:System.String

值未更改。

Return Value
Type: System.String
value is returned unchanged.


Convert.ToString(object o);
Convert.ToString(string s);





C#编译器本质上试图选择最适合输入的特定重载。空值可转换为任何引用类型。在这种情况下,字符串比对象更具体,因此它将被选为赢家。



在null as对象中,您将表达式的类型固化为宾语。这意味着它不再与字符串重载兼容,并且编译器选择对象重载,因为它是剩下的唯一兼容的。



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.

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.


这篇关于什么时候null不是null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 19:36