为什么值类型不能为null [英] Why value types can't be 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>
是一个 hasValue的
标记值类型,可以是假
来表示没有任何价值。它仍然有一个值(当 hasValue的
是假
,值
是默认(T)
),但 hasValue的
标记告诉你忽略的价值。
它无关,与空
,除了CLR自动unboxes 空
盒装值到可空< T>
与 hasValue的
设置为假
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屋!