问题
I have a situation where I need to compare nullable types.
Suppose you have 2 values:
int? foo=null;
int? bar=4;
This will not work:
if(foo>bar)
The following works but obviously not for nullable as we restrict it to value types:
public static bool IsLessThan<T>(this T leftValue, T rightValue) where T : struct, IComparable<T>
{
return leftValue.CompareTo(rightValue) == -1;
}
This works but it's not generic:
public static bool IsLessThan(this int? leftValue, int? rightValue)
{
return Nullable.Compare(leftValue, rightValue) == -1;
}
How do I make a Generic version of my IsLessThan
?
Thanks a lot
回答1:
Try this:
public static bool IsLessThan<T>(this Nullable<T> t, Nullable<T> other) where T : struct
{
return Nullable.Compare(t, other) < 0;
}
回答2:
It can be simplified:
public static bool IsLessThan<T>(this T? one, T? other) where T : struct
{
return Nullable.Compare(one, other) < 0;
}
来源:https://stackoverflow.com/questions/6561697/creating-a-nullablet-extension-method-how-do-you-do-it