【发布时间】:2017-05-04 07:44:23
【问题描述】:
如果我们将某个 null 变量转换为一个类型,我希望编译器会抛出一些异常,但事实并非如此。为什么?
我是说
string sample1 = null as string;
string sample2 = (string)null;
object t1 = null;
TestClass t2 = (TestClass)t1;
也许在第一个中,as 运算符处理异常处理。但其他示例必须抛出异常。编译器如何处理这些情况?也许由于变量为空,它不执行强制转换操作?因为如果它真的强制转换为空指针,那一定是一个错误。
【问题讨论】:
-
我没有看到这里的问题,所有这些类型(很可能是 TestClass 的情况)都是可以为空的,因此可以被强制转换
-
+1 @AlfieGoodacre 只要对引用类型 (
class) 而不是值类型 (struct) 进行转换。那么你应该一切都好。 -
字符串可以赋值为null,即string str = null;
-
另外假设你有两个重载
MyMethod(Foo foo)和MyMethod(Bar bar)并且想在第一个上传递null。你会怎么做?MyMethod((Foo)null)或MyMethod(null as Foo). -
查看 Eric Lippert 在这个问题 stackoverflow.com/a/3652872/1587082 中的回答,了解 null 的工作原理。
标签: c# casting compiler-errors null nullreferenceexception