我有一种情况需要比较可空类型.
假设您有2个值:
int? foo=null;
int? bar=4;
Run Code Online (Sandbox Code Playgroud)
这不起作用:
if(foo>bar)
Run Code Online (Sandbox Code Playgroud)
以下工作,但显然不是可空的,因为我们将其限制为值类型:
public static bool IsLessThan<T>(this T leftValue, T rightValue) where T : struct, IComparable<T>
{
return leftValue.CompareTo(rightValue) == -1;
}
Run Code Online (Sandbox Code Playgroud)
这有效,但它不通用:
public static bool IsLessThan(this int? leftValue, int? rightValue)
{
return Nullable.Compare(leftValue, rightValue) == -1;
}
Run Code Online (Sandbox Code Playgroud)
如何制作我的通用版本IsLessThan?
非常感谢
Sea*_*man 18
试试这个:
public static bool IsLessThan<T>(this Nullable<T> t, Nullable<T> other) where T : struct
{
return Nullable.Compare(t, other) < 0;
}
Run Code Online (Sandbox Code Playgroud)