问题:

我是C#的新手,不明白为什么以下代码不起作用。

public static Nullable<T> CoalesceMax<T>(Nullable<T> a, Nullable<T> b) where T : IComparable
{
    if (a.HasValue && b.HasValue)
        return a.Value.CompareTo(b.Value) < 0 ? b : a;
    else if (a.HasValue)
        return a;
    else
        return b;
}

// Sample usage:
public DateTime? CalculateDate(DataRow row)
{
    DateTime? result = null;
    if (!(row["EXPIRATION_DATE"] is DBNull))
        result = DateTime.Parse((string)row["EXPIRATION_DATE"]);
    if (!(row["SHIPPING_DATE"] is DBNull))
        result = CoalesceMax(
            result
            DateTime.Parse((string)row["SHIPPING_DATE"]).AddYears(1));
    // etc.
    return result;
}

它在编译期间出现以下错误:


类型’T’必须是非可空值类型,以便在泛型类型或方法’System.Nullable <T>’中将其用作参数’T’

I’m new to C# and don’t understand why the following code doesn’t work.It gives the following error during compilation:The type ‘T’ must be a non-nullable value type in order to use it as parameter ‘T’ in the generic type or method ‘System.Nullable<T>’