为什么可空< T> HasValue属性不是空值抛出NullReferenceException异常? [英] Why does Nullable<T> HasValue property not throw NullReferenceException on Nulls?

查看:198
本文介绍了为什么可空< 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.

当你写日期时间?,这仅仅是速记<一个href="http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx"><$c$c>Nullable<DateTime>,这是一个结构。有没有办法让这个在技术上是无效的,因为它不是一个引用类型。

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屋!

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