如何创建Between Extension方法

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

我想检查一下

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(this T1 val1, T1 lowest, T1 highest) where ???? { What code to write here???? } 

你可以这样做:

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

参考这里

或者,如果您想在集合上执行此操作,则可以执行以下操作:

 public static IEnumerable Between ( this IEnumerable source, Func selector, TResult lowest, TResult highest ) where TResult : IComparable { 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); 

也许是这样的:

 public static bool Between(this T1 val1, T2 lowest, T2 highest) where T1 : IComparable where T2 : IComparable { return val1.CompareTo(lowest) > 0 && val1.CompareTo(highest) < 0; } 

混合类型会使其变得更难,例如。 如果T1是datetime而t2是int那么你期望什么行为?

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

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