且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

帮助与C#泛型错误 - "类型'T'必须是一个非空值类型"

更新时间:2022-10-27 07:40:54

您需要添加一个T:结构约束:

 公共静态可空< T> CoalesceMax< T> 
(可空< T>一种,可为空< T> b)若T:结构,IComparable的

否则C#将设法制定出什么可空< T> 表示,并认识到,它已经没有要求可空&LT约束; T> 本身。换句话说,你可以尝试拨打:

  CoalesceMax<串>(...)

这是没有意义的,因为可空<串> 不是有效的。


I'm new to C# and don't understand why the following code doesn't work.

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

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>'

You need to add a T : struct constraint:

public static Nullable<T> CoalesceMax<T>
    (Nullable<T> a, Nullable<T> b) where T : struct, IComparable

Otherwise C# will try to work out what Nullable<T> means, and realise that it doesn't already have the constraint required by Nullable<T> itself. In other words, you could try to call:

CoalesceMax<string>(...)

which wouldn't make sense, as Nullable<string> isn't valid.