工作中不小心写了下面这行代码:
string x = (object) null;
// It was var x = (object)null and I changed from var to string instead of
// object x = null;
这给了我一个类似这样的编译错误:Can't cast source type object to target type string
为什么?是不是 null
只是一堆指向“无处”内存地址的零,无论类型是什么?
最佳答案
问题不在于 null
的转换,而是 object
无法分配给 string
。这很好用
string x = (string)null;
在 C# 语言规范的第 2.4.4.6 节中列出了如果您删除强制转换 (string x = null
) 会起作用的原因
The null-literal can be implicitly converted to a reference type or nullable type
在您引入强制转换 ((object)null
) 的那一刻,您就不再拥有空文字。相反,您有一个 object
类型的值。本质上和
object temp = null;
string x = temp;
关于c# - 转换 null 不编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9008339/