将空值转换为类型 [英] Cast null value to a type

查看:69
本文介绍了将空值转换为类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题。
,如果我们将一些null变量转换为类型。我希望编译器抛出一些异常,但事实并非如此。我真的很想知道为什么。
我的意思是

I have a simple question. if we cast some null variable to a type. I expect compiler to throw Some Exception, but it is not. And I realy want to know the reason why. I mean

string sample1 = null as string;
string sample2 = (string)null;


object t1 = null;
TestClass t2 = (TestClass)t1; 

可能在第一个中,因为运算符处理异常处理。但是其他样本必须抛出异常。编译器如何处理这些情况,也许由于变量为null,它不执行强制转换操作?因为如果它真的强制转换为空指针,那肯定是一个错误。

maybe in the first one, as operator handles the exception handling. But others samples must throw exception. How compiler handles these situations , maybe since the variables are null , it does not perform cast operation? Cause if it really cast a null pointer it must be an error.

推荐答案

根据文档(显式转换),您可以将基本类型转换为派生类型。

According to the documentation (Explicit conversions) you can cast from a base type to a derived type.

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

Since null is a valid value for all reference types, as long as the cast route exists you should be fine.

object null→ TestClass null充当 object 是所有引用类型的超类。

object null → TestClass null works as object is a superclass to all reference types.

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

However, if you try string null → TestClass null (Assuming TestClass is not a subtype of string), you will find a compilation error as TestClass is not a derived type of string.

这篇关于将空值转换为类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆