Nullable DateTime是否正确? [英] Is Nullable DateTime work correct?

查看:205
本文介绍了Nullable DateTime是否正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请检查以下代码

  DateTime? tmp = new DateTime(); 
tmp = null;
return tmp.ToString();

它返回 String.Empty 。 p>

是否正确?



可能会在第二行代码中上升异常。

解决方案

是的,这是正确的。从文档


如果 HasValue Nullable< T> 对象的值的文本表示如果 HasValue 属性为false,则$ c>属性为true或空字符串()。 p>

还要注意 Nullable< T> .Equals Nullable< T> .GetHashCode 不要在这种情况下抛出,但是 抛出 Nullable< T> .GetType 这是因为 Object.Equals Object.GetHashCode Object.ToString 被覆盖为 Nullable< T> ,但是 Object.GetType 不是(因为它不能它没有标记为 virtual )。


Please check following code

DateTime? tmp = new DateTime();
tmp = null;
return tmp.ToString();

It returns String.Empty.

Is it correct?

May be it will be better to rise exception in second line of code

解决方案

Yes, it's correct. From the documentation

The text representation of the value of the current Nullable<T> object if the HasValue property is true, or an empty string ("") if the HasValue property is false.

Note also that Nullable<T>.Equals and Nullable<T>.GetHashCode do not throw in this case but that Nullable<T>.GetType does throw. This is because Object.Equals, Object.GetHashCode and Object.ToString are overridden for Nullable<T> but that Object.GetType is not (because it can not be as it is not marked as virtual).

这篇关于Nullable DateTime是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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