为什么可空&LT; T&GT; HasValue属性不是空值抛出NullReferenceException异常? [英] Why does Nullable<T> HasValue property not throw NullReferenceException on Nulls?
问题描述
考虑以下code:
DateTime? ndate = null;
Console.WriteLine(ndate.HasValue);
我本来期望一个NullReferenceException,但hasValue的确实将返回false。然而,由于ndate为null,如何属性调用成功,因为没有对象调用的财产hasValue的?
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.
当你写日期时间?
,这仅仅是速记<一个href="http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx"><$c$c>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.
这篇关于为什么可空&LT; T&GT; HasValue属性不是空值抛出NullReferenceException异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!