为什么这个不能编译?无法从“X”转换?到“X”

m4d*_*ign 0 .net c# nullable

我遇到了一个意外的问题(或者这是预期的行为?)。以下代码未编译,并给出错误:

CS1503 Argument 1: cannot convert from 'long?' to 'long'

public static void Add(long? ticks)
{
    if (ticks != null)
    {
        new DateTime(ticks);
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

没有从Nullable<T>到 的隐式转换T- 您可以通过强制转换显式执行此转换,例如new DateTime((long) ticks),或使用Value属性,例如new DateTime(ticks.Value)

作为我现在通常更喜欢的替代方案,您可以使用 C# 7 中的模式匹配来使其稍微简单一些,在检查非空值的同一步骤中提取空值:

public static void Add(long? ticks)
{
    // This will match if ticks is non-null, and assign the value
    // into the newly-introduced variable "actualTicks"
    if (ticks is long actualTicks)
    {
        var dt = new DateTime(actualTicks);
        // Presumably use dt here
    }
}
Run Code Online (Sandbox Code Playgroud)