帮助解决 C # 泛型错误-“类型‘ T’必须是非空值类型”

我是 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”中将其用作参数“ T”。可空 < T >’
80782 次浏览

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.

Your generic method is using a Nullable<T>.

However, you aren't constraining the type of T, so it could end up being Nullable<Form>, which is obviously invalid.

You need to change the constraint to where T : struct, IComparable to ensure that T can only be a value type.

The Nullable<T> type has a constraint on it that requires T to be a value type (struct in C#). That's why the compiler is telling you about Nullable<T> and not your function or the call site of that function -- it's the Nullable class that is the root cause of the error, so this is actually more helpful that if the compiler just pointed to your function and said "this ain't right, fix it!" (Imagine if CoalesceMax used several generics, and violated the constraint on only one of them - it's more useful to know which generic had its constraint broken than to just know that one or more constraints in CoalesceMax were broken).

The solution is to make your T and their T compatible by introducing the same constraint. This is done by adding the struct constraint, which must come before all interface / new constraints:

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

Not exactly an answer to the OP but since this was the first thing that popped up on google for the same error message, I had to add the constraint on my class definition, rather than my method, eg

public class MyClass<T> where T : struct
{
public void MyMethod(T? value)
{
}
}