【发布时间】:2012-01-25 18:43:17
【问题描述】:
在工作中不小心写了下面这行代码:
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 不只是一堆指向“无处”内存地址的零吗?
【问题讨论】:
-
你为什么不分配
string x = string.empty;? -
为什么要投?
string x = null.. -
如果你刚刚说
string x = null;,你就不会遇到这个问题。但这不是你说的。你说string x = someObj;其中 someObj 是一个object恰好是一个空值。就编译器而言,您有一个试图分配给字符串的对象引用,这是不合法的。 -
@harold。你是对的,这是错误的,但我仍然很感兴趣。
-
您需要显式转换才能将
object引用向下转换为string。因此使用string x = (string)(object)null;。正确的? ;-)
标签: c# .net compiler-construction null