【发布时间】:2012-02-18 23:40:57
【问题描述】:
以Casting null doesn't compile 为灵感,来自 Eric Lippert 的评论:
这展示了一个有趣的案例。 “uint x = (int)0;”将 即使 int 不能隐式转换为 uint,也会成功。
我们知道这不起作用,因为object 不能分配给string:
string x = (object)null;
但这确实如此,虽然直觉上它不应该:
uint x = (int)0;
当int 不能隐式转换为uint 时,为什么编译器允许这种情况?
【问题讨论】:
-
我想
unit x = 0工作的原因相同。0是有符号整数,除非您指定unit x = 0U。 -
可能是 6.1.9 的规范和 int 转换的折扣,因为 0 已经是一个 int。虽然通常 int 不能隐式转换为 uint (6.1.2),但可以转换 int 类型的 常量表达式。
-
那么
0作为常量表达式隐含的值是什么?编译器是否只是忽略(int)显式转换并将0视为uint常量? -
见this Eric Lippert 的回答。
-
@Yuck,编译器看到了一个
int常量。但是,它也知道非负的int常量可以安全地转换为uint。
标签: c# .net compiler-construction type-conversion implicit-conversion