5

我有一个变量,其值在运行时填充。我想使用扩展方法检查该值是否介于两个相同的数据类型值(例如最低和最高)之间。

我想检查一下

int a = 2; //here static but is can be changed at runtime

if(a.Between(0,8))
   DoSomething();
else
   DoNothing();

如果a是 0 或 8 或它们之间的任何值,它应该返回true.

如果a是(-1 或更小)或(9 或更大),那么它应该返回false

我想创建一个扩展方法,比如

public static bool Between<T1>(this T1 val1, T1 lowest, T1 highest) where ????
{
    What code to write here???? 
}
4

3 回答 3

15

你可以这样做:

public static bool Between<T>(this T actual, T lower, T upper) where T : IComparable<T>
{
    return actual.CompareTo(lower) >= 0 && actual.CompareTo(upper) <= 0;
}

参考这里

或者,如果您想在集合上执行此操作,您可以这样做:

public static IEnumerable<TSource> Between<TSource, TResult>
(
    this IEnumerable<TSource> source, Func<TSource, TResult> selector,
    TResult lowest, TResult highest
)
    where TResult : IComparable<TResult>
{
    return source.OrderBy(selector).
        SkipWhile(s => selector.Invoke(s).CompareTo(lowest) < 0).
        TakeWhile(s => selector.Invoke(s).CompareTo(highest) <= 0 );
}

参考这里

用法:

var tenTo40 = list.Between(s => s, 10, 40);
于 2012-05-09T06:50:41.333 回答
1

混合类型会使它更难,例如。如果 T1 是 datetime 并且 t2 是 int 那么你期望什么行为?

只使用一种类型就可以使用 IComparable 接口

public static bool Between<T>(this T self, T lower,T higher) where T : IComparable
{
    return self.CompareTo(lower) >= 0 && self.CompareTo(higher) <= 0;
}
于 2012-05-09T06:49:55.370 回答
1

也许是这样的:

public static bool Between<T1, T2>(this T1 val1, T2 lowest, T2 highest) where T1 : IComparable where T2 : IComparable {
    return val1.CompareTo(lowest) > 0 && val1.CompareTo(highest) < 0;
}
于 2012-05-09T06:54:56.863 回答