可为空的类型很有用,但一开始有时会造成混淆。的Nullable<T>是一个结构,其中T是一个结构为好。该结构包装实例变量T的值,并公开三个主要成员。
HasValue // Returns bool indicating whether there is a value present.
Value // Returns the value of T if one is present, or throws.
GetValueOrDefault() // Gets the value or returns default(T).
Run Code Online (Sandbox Code Playgroud)
您可以通过?在变量类型的声明后添加' '或Nullable<在此处将变量类型包装为可变类型来使任何结构可为空>。如下图所示:
Nullable<DateTimeOffset> a = null;
DateTimeOffset? b = null;
Run Code Online (Sandbox Code Playgroud)
我相信您要在此处检查的是是否确实存在一个值,.HasValue然后.Value从偏移量中提取并执行标准转换。
例
var now = DateTime.Now;
DateTimeOffset? offset = now;
DateTime dateTime = offset.HasValue ? offset.Value.DateTime : DateTime.MaxValue;
Run Code Online (Sandbox Code Playgroud)
或者,如果您想DateTime?要这样做:
var now = DateTime.Now;
DateTimeOffset? offset = now;
DateTime? dateTime = offset.HasValue ? offset.Value.DateTime : (DateTime?)null;
Run Code Online (Sandbox Code Playgroud)