c# - 转换 null 不编译

标签 c# .net compiler-construction null

工作中不小心写了下面这行代码:

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/

相关文章:

javascript - 在 Telerik RadPageView 完成加载后调用 JavaScript 函数?

c# - 我可以尝试在 catch 中打开 MySQL 连接吗?

c# - 在 C# 中将字符串转换为 float

c# - 使用 Mono 的 mcs 使用 Tuple 编译代码

c# - 使用XPath根据同一节点中的另一个属性查找节点中的属性值?

c - 编译器实现中 x++ 和++x 的区别

compiler-construction - LR(1) 但不是 LL(1) 的语法

c++ - 编译器或链接器内联函数的差异?

c# - 没有服务定位器的 IFilterProvider 注入(inject)

c# - Windows 编程 : Simple SFTP Transfer Application