创建一个可以为空的<T>扩展方法,你是怎么做到的?

use*_*969 15 c# nullable

我有一种情况需要比较可空类型.
假设您有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)

  • 您可能希望使返回读取Nullable.Compare(t,other)<0以符合Compare文档.对于"小于大小写",Compare方法应该返回小于0的值.http://msdn.microsoft.com/en-us/library/dxxt7t2a.aspx (3认同)