[英]template class for nullables on primitive types
我想實現以下目標:
int? a = 1;
int? b = 2;
int? smallerInt = NullableOps<int>.Min(a, b);
float? c = 1;
float? d = 2;
float? smallerFloat = NullableOps<float>.Min(a, b);
目前NullableOps
是:
public class NullableOps<T>
{
public static Nullable<T> Min(Nullable<T> a, Nullable<T> b)
{
// do some stuff
var x = a.Value < b.Value ? a : b; // error here: '<' can't be applied to operand T and T
}
}
但它有像T must not be a nullable type
這樣的錯誤。 所以我必須使用 function 重載為不同類型復制相同的代碼:
public class NullableOps
{
public static int? Min(int? a, int? b)
{
// do stuff
}
public static float? Min(float? a, float? b)
{
// do stuff
}
}
但我不想這樣做,因為每次添加新類型時,我都需要再次復制代碼。 有人可以幫忙嗎?
您需要添加以下約束。
public class NullableOps<T> where T : struct
該錯誤描述編譯器無法保證參數類型T
不會為非空。
當您使用Nullable<T>
時,類型參數T
必須是不可為空的值類型,例如int,float
。 (它不能是int?
)。 您可以通過使用T
是值類型(結構)的約束來強制執行此操作
更新:基於編輯
基於 OP 中的更新,您需要添加IComparable<T>
約束並使用CompareTo
而不是“<”。 例如,
public class NullableOps<T> where T : struct,IComparable<T>
{
public static Nullable<T> Min(Nullable<T> a, Nullable<T> b)
{
return a.Value.CompareTo(b.Value) < 0 ? a : b;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.