为什么值类型不能为null [英] Why value types can't be null

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

问题描述

我知道这是可能的有包装的价值类型,并给出存储空能力的空值类型。 但有一个技术上的原因不允许值类型为空或原因仅仅是概念上的?

I know that it is possible to have Nullable value types that wraps the value type and gives ability to store null. But is there a technical reason do not allow the value type to be null or the reason is only conceptual?

推荐答案

一个引用类型storeed为基准(如指针)一个对象实例。
表示引用未指向一个对象的实例。

A reference type is storeed as a reference (like a pointer) to an object instance.
null means a reference that isn't pointing to an instance of an object.

值类型被存储为值本身,而没有任何参考文献。
因此,它没有任何意义有一个值类型和mdash;值类型的定义的包含值

Value types are stored as the values themselves, without any references.
Therefore, it doesn't make sense to have a null value type—the value type by definition contains a value.

可空< T> 是一个 hasVa​​lue的标记值类型,可以是来表示没有任何价值。它仍然有一个值(当 hasVa​​lue的默认(T)),但 hasVa​​lue的标记告诉你忽略的价值。
它无关,与,除了CLR自动unboxes 盒装值到可空< T> hasVa​​lue的设置为

Nullable<T> is a value type with a HasValue flag that can be false to indicate that there is no value. It still has a value (when HasValue is false, Value is default(T)), but the HasValue flag tells you to ignore the value.
It has nothing to do with null, except that the CLR automatically unboxes null boxed values to a Nullable<T> with HasValue set to false.

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

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