如果我有一个方法:
protected int CalculateActualDuration(DateTime? startDate, DateTime? endDate) {
if (startDate.HasValue && endDate.HasValue) {
return Math.Abs((int)(endDate.Value.Subtract(startDate.Value).TotalMinutes));
}
else {
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
我可以通过传入DateTime来调用该方法吗?和一个DateTime.那么编译器如何理解这种差异呢?
这是否意味着如果我传入一个DateTime值,那么if语句基本上就像是一样
if (true && true)
Run Code Online (Sandbox Code Playgroud)
并且所有*.value都已更改为正确的对象?那么所有endDate.Value现在都是EndDates?
编译器是否在运行时将所有非Nullables参数转换为Nullables?
Gra*_*ICA 10
方法中的所有内容都保持不变,startDate而且endDate参数仍然是Nullable<T>结构的实例.
将"正常" DateTime传递给方法时,您将利用结构中指定的隐式转换Nullable<T>:
public static implicit operator Nullable<T>(T value) {
return new Nullable<T>(value);
}
Run Code Online (Sandbox Code Playgroud)
从上面链接的MSDN页面:
如果value参数不为null,则将新Nullable值的Value属性初始化为value参数,并将HasValue属性初始化为true.