创建一个可为空的<T>扩展方法,你是怎么做的? [英] Creating a nullable&lt;T&gt; extension method ,how do you do it?

查看:44
本文介绍了创建一个可为空的<T>扩展方法,你是怎么做的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了需要比较可为空类型的情况.
假设您有 2 个值:

I have a situation where I need to compare nullable types.
Suppose you have 2 values:

int? foo=null;
int? bar=4;

这行不通:

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;
}

如何制作我的 IsLessThan 的通用版本?

How do I make a Generic version of my IsLessThan?

非常感谢

推荐答案

试试这个:

public static bool IsLessThan<T>(this Nullable<T> t, Nullable<T> other) where T : struct
{
    return Nullable.Compare(t, other) < 0;
}

这篇关于创建一个可为空的<T>扩展方法,你是怎么做的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆