编译器如何理解Nullables?

时间:2015-02-09 01:09:27

标签: c# nullable

如果我有方法:

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;
        }
    }

我可以通过传入DateTime来调用该方法吗?和一个DateTime。那么编译器如何理解这种差异呢?

这是否意味着如果我传入DateTime值,if语句基本上就像

那样
if (true && true)

并且所有* .value都已更改为正确的对象?那么所有endDate.Value现在都是EndDates?

编译器是否在运行时将所有非Nullables参数转换为Nullables?

1 个答案:

答案 0 :(得分:10)

您方法中的所有内容都保持不变,startDateendDate参数仍然是Nullable<T> struct的实例。

当您将“正常”DateTime传递给该方法时,您将利用Nullable<T>结构中指定的implicit conversion

public static implicit operator Nullable<T>(T value) {
    return new Nullable<T>(value);
}

从上面链接的MSDN页面:

  

如果参数不是 null ,则新Value值的Nullable属性将初始化为value参数和{ {3}}属性已初始化为 true

相关问题