Nullable DateTime是否正确? [英] Is Nullable DateTime work correct?
问题描述
请检查以下代码
DateTime? tmp = new DateTime();
tmp = null;
return tmp.ToString();
它返回 String.Empty
。 p>
是否正确?
可能会在第二行代码中上升异常。
是的,这是正确的。从文档
如果
HasValue $ c,则当前
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 theHasValue
property is true, or an empty string (""
) if theHasValue
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屋!