Creating a nullable<T> extension method ,how do you do it?

流过昼夜 提交于 2019-12-10 01:34:55

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!