Creating a nullable extension method ,how do yo

2020-08-10 07:42发布

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

标签: c# nullable
2条回答
聊天终结者
2楼-- · 2020-08-10 08:01

Try this:

public static bool IsLessThan<T>(this Nullable<T> t, Nullable<T> other) where T : struct
{
    return Nullable.Compare(t, other) < 0;
}
查看更多
Anthone
3楼-- · 2020-08-10 08:04

It can be simplified:

public static bool IsLessThan<T>(this T? one, T? other) where T : struct
{
    return Nullable.Compare(one, other) < 0;
}
查看更多
登录 后发表回答