为什么作为字符串的nullable int在c#中为null?

时间:2017-01-23 13:50:31

标签: c#

由于某种原因,未知visualstudio告诉我此代码无法访问:

            int? newInt = null;
            string test = newInt.ToString();
            if (test == null)
            {
                //unreachable Code
            }

感谢您的帮助! :)

3 个答案:

答案 0 :(得分:5)

string test = newInt.ToString();
如果将其转换为string

test将永远不会为null。当你转换它时,它将变成空字符串。

int? newInt = null;
string test = newInt.ToString();
if (test == "")
    {
        Console.WriteLine("Hello World"); //Reaches the code
    }

答案 1 :(得分:1)

因为:

((int?)null).ToString() == string.Empty

可空int的返回值是一个空字符串。 if块中的代码确实检查了永远不存在的空值。这只能起作用,因为int?是一种框架类型,ToString()的行为是已知且不可变的。如果您在用户定义的值类型上尝试此操作,则无法进行相同的断言。

答案 2 :(得分:0)

.ToString()不能允许空值。

您可以使用:

 convert.ToString(newInt)

检查条件:

 "string.IsNullOrEmpty(test))"
相关问题