【问题标题】:Cast null value to a type将空值转换为类型
【发布时间】: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


【解决方案1】:

According to the documentation(显式转换)您可以从基类型强制转换为派生类型。

由于null 是所有引用类型的有效值,所以只要转换路线存在就可以了。

object null → TestClass null 作为object 是所有引用类型的超类。

但是,如果你尝试string null → TestClass null(假设TestClass 不是string 的子类型),你会发现编译错误,因为TestClass 不是@987654331 的派生类型@。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多