首页 > 解决方案 > 为什么不编译?无法从“X”转换?到“X”

问题描述

我面临一个意想不到的问题(或者这是预期的行为?)。以下代码不编译,它给了我错误:

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

public static void Add(long? ticks)
{
    if (ticks != null)
    {
        new DateTime(ticks);
    }
}

标签: c#.netnullable

解决方案


没有从Nullable<T>to的隐式转换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
    }
}

推荐阅读