无法隐式转换'System.TimeSpan?' 到'System.TimeSpan'

Bil*_*med 4 c# datetime timespan asp.net-mvc-5

以下代码工作正常:

DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(-1);
int d3 = (int)(d1 - d2).TotalDays;
Run Code Online (Sandbox Code Playgroud)

但是,如果我定义DateTimeDateTime?:

DateTime? d1 = DateTime.Now;
DateTime? d2 = DateTime.Now.AddDays(-1);
int d3 = (int)(d1 - d2).TotalDays;
Run Code Online (Sandbox Code Playgroud)

带下划线的红色错误

无法隐式转换'System.TimeSpan?' 到'System.TimeSpan'

是否可以获得定义为可为空的两个日期时间之间的天数差异?

Jon*_*eet 11

是的,但你需要使用该Value属性"取消空"它:

int d3 = (int)(d1 - d2).Value.TotalDays;
Run Code Online (Sandbox Code Playgroud)

但是,你应该考虑的可能性,要么d1d2为空-这不会在你的情况发生,但可能在其他情况下.你可能想要:

int? d3 = (int?) (d1 - d2)?.TotalDays;
Run Code Online (Sandbox Code Playgroud)

这将会给的结果,null如果任一d1或者d2null.这假设您正在使用C#6,否则?.操作员将无法使用.

(您可以GetValueOrDefault()按照user3185569的建议在第一种情况下使用,但是TimeSpan如果任何一个值都是静默使用空的null,那感觉不太可能是您想要的.)

  • GetValueOrDefault()的使用是给定代码的合理优化,适用于已知可空值不为空的其他情况(大多数情况下是在经过精确测试的分支之后),但与所有优化一样,知道何时不使用它比知道它所提供的微选项更为重要。 (2认同)

Zei*_*kki 5

Yes, using GetValueOrDefault():

DateTime? d1 = DateTime.Now;
DateTime? d2 = DateTime.Now.AddDays(-1);
int d3 = (int)(d1 - d2).GetValueOrDefault().TotalDays;
Run Code Online (Sandbox Code Playgroud)

d1 - d2 return Nullable TimeSpan which doesn't directly contains a property called TotalDays. But using GetValueOrDefault() you can return a TimeSpan object and get 0 Total Days if the value was NULL

If you do really expect Null Values, it is better to differentiate between 0 days (What the above approach returns) and and invalid operation (date - null), (null - date) and (null - null). Then you might need to use another approach:

int? d3 = (int) (d1 - d2)?.TotalDays;
Run Code Online (Sandbox Code Playgroud)

Or if you're using a version prior to C# 6 :

int? d3 = d1.HasValue && d2.HasValue ? (int)(d1 - d2).Value.TotalDays : new int?();
Run Code Online (Sandbox Code Playgroud)