我有一个变量,其值在运行时填充。我想检查该值是否介于两个相同的数据类型值(比如最低和最高)之间,或者是否使用扩展方法。
我想检查一下
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????
}
答案 0 :(得分:14)
你可以这样做:
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;
}
参考here
或者如果你想在集合上这样做,你可以这样做:
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 );
}
参考here
用法:
var tenTo40 = list.Between(s => s, 10, 40);
答案 1 :(得分: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;
}
答案 2 :(得分:0)
混合类型会使其变得更难,例如。如果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;
}