为什么不能在c#中为空字符串为null?
问题描述:
出于某种原因不明visualstudio
告诉我这个代码是无法访问:为什么不能在c#中为空字符串为null?
int? newInt = null;
string test = newInt.ToString();
if (test == null)
{
//unreachable Code
}
谢谢您的帮助! :)
答
string test = newInt.ToString();
如果将其转换为string
,测试将永远不会为空。当你转换它时,它将变成空字符串。
int? newInt = null;
string test = newInt.ToString();
if (test == "")
{
Console.WriteLine("Hello World"); //Reaches the code
}
答
因为:
((int?)null).ToString() == string.Empty
从可为空的INT返回值是一个空字符串。 if块中的代码确实检查了一个永远不可能存在的空值。这只适用于因为int?
是一个框架类型,并且ToString()
的行为是已知且不可变的。如果您尝试使用用户定义的值类型,则无法创建相同的断言。
答
.ToString()
不能允许空值。
您可以使用:
convert.ToString(newInt)
检查条件是:
"string.IsNullOrEmpty(test))"
+0
It * can *。它*不*。如果设计者已经决定这就是他们想要做的事情,那么没有什么能阻止它返回null。 – Servy
试着运行一下,看看'test'设置为。但是,如果你做了'newInt?.ToString()',那么'test'就是'null'。事实上,你可能会问为什么它不会抛出一个空引用异常,这有点儿有趣。 – juharr
使用if(string.IsNullOrEmpty(test))代替 –
['Nullable .ToString'](https://msdn.microsoft.com/en-us/library/9hd15ket(v = vs.110))的文档。 ASPX)指出,如果'HasValue'是'FALSE'(当你设置一个可为空''到'null'是哪种情况) –
juharr