开发者

Nullable types in .NET missing methods

I noticed today that if you declare a nullable DateTime object you don't get the same set of functions as you do when you have a standard DateTime object.

For example:

DateTime? nullableDT = DateTime.Now;
DateTime regularDT = DateTime.Now;

in the code above nullableDT cannot use any of the following functions:

ToFileTime
ToFileTimeUtc
ToLocalTime
ToLongDateString
ToLongTimeString
ToOADate
ToShortDateString
ToShortTimeString
ToString(IFormatProvider)
ToString(String)
ToString(String, IFormatProvider)
ToUniversalTime

This is the short list, there are many more methods not available.

Why is .NET behaving like this? I work开发者_开发百科ed around it by throwing a Convert.ToDateTime() around my nullable date but that seems krufty... Is there a better way?


That's because you need to call Nullable<T>.Value to get the actual DateTime value.


A Nullable<T> isn't a T, it just wraps a T. So it doesn't have the members defined on T. If you want to access the methods of T, you can do that:

if (nullableDT.HasValue)
{
    Console.WriteLine(nullableDT.Value.ToShortTimeString());
    ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜