相关疑难解决方法(0)

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

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

非常感谢

c# nullable

15
推荐指数
1
解决办法
7304
查看次数

标签 统计

c# ×1

nullable ×1