为什么可空< T> HasValue属性不是空值抛出NullReferenceException异常?

问题描述:

考虑以下code:

DateTime? ndate = null;
Console.WriteLine(ndate.HasValue);

我本来期望一个NullReferenceException,但hasVa​​lue的确实将返回false。然而,由于ndate为null,如何属性调用成功,因为没有对象调用的财产hasVa​​lue的?

I would have expected a NullReferenceException, but HasValue will indeed return false. However, since ndate is null, how does the property invocation succeed, since there is no object to invoke the property HasValue on?

从技术上讲,ndate不为空 - 它是值类型,与它的值指定为空

Technically, "ndate" is not null - it is a value type, with it's value specified as being null.

当你写日期时间?,这仅仅是速记Nullable<DateTime>$c$c>,这是一个结构。有没有办法让这个在技术上是无效的,因为它不是一个引用类型。

When you write DateTime?, this is just shorthand for Nullable<DateTime>, which is a struct. There is no way for this to technically be null, since it's not a reference type.