帮助与C#泛型错误 - "类型'T'必须是一个非空值类型" [英] Help with C# generics error - "The type 'T' must be a non-nullable value type"
本文介绍了帮助与C#泛型错误 - "类型'T'必须是一个非空值类型"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新的C#和不明白为什么下面的代码无法正常工作。
公共静态可空< ; T> CoalesceMax< T>(可空< T>一种,可为空< T> b)若T:IComparable的
{
如果(a.HasValue&安培;&安培; b.HasValue)
返回。 Value.CompareTo(b.Value)LT; 0?乙:一个;
,否则如果(a.HasValue)
返回;
,否则
回复B;
}
//使用示例:
公众的DateTime? CalculateDate(DataRow的行)
{
日期时间?结果= NULL;
如果((行[EXPIRATION_DATE]是的DBNull)!)
结果= DateTime.Parse((字符串)行[EXPIRATION_DATE]);
如果(!(行[SHIPPING_DATE]是的DBNull))
结果= CoalesceMax(
结果
DateTime.Parse((字符串)行[SHIPPING_DATE])。 AddYears(1));
//等
返回结果;
}
据编译过程中提供了以下错误:
<块引用>类型'T'必须是为了用它作为参数T中的泛型类型或方法非空值类型'System.Nullable< T> 块引用>
解决方案
您需要添加一个T:结构约束:
公共静态可空< T> CoalesceMax< T>
(可空< T>一种,可为空< T> b)若T:结构,IComparable的
否则C#将设法制定出什么可空< T>
表示,并认识到,它已经没有要求可空<约束; 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.
这篇关于帮助与C#泛型错误 - "类型'T'必须是一个非空值类型"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文