人员生日 IsBetween 示例代码如下:
var p1= new Person{ Name = "鹤冲天", Birthday = new DateTime(1990, 1, 1)}; var p2= new Person{ Name = "鹤中天", Birthday = new DateTime(2000, 1, 1)}; var p3= new Person{ Name = "鹤微天", Birthday = new DateTime(2010, 1, 1)}; bool b6 = p2.IsBetween(p1, p3, new PersonBirthdayComparer());
类似,我们还可以对人员进行身高、体重、人品等其它方面的 IsBetween 判断,只需要传入不同的 comparer。
针对 IComparable 接口的 IsBetween 扩展
之前一篇文章中,我曾说过要针对接口扩展,我们何不针对 IComparable 接口 进行扩展呢:
public static bool IsBetween(this IComparable t, T lowerBound, T upperBound, bool includeLowerBound = false, bool includeUpperBound = false)
{ if (t == null) throw new ArgumentNullException("t"); var lowerCompareResult = t.CompareTo(lowerBound); var upperCompareResult = t.CompareTo(upperBound); return (includeLowerBound && lowerCompareResult == 0) || (includeUpperBound && upperCompareResult == 0) || (lowerCompareResult > 0 && upperCompareResult < 0);
}
这个扩展的应用场景可能不多,这里举一个方便大家理解,假定我们自定义了一个大整数类形:
public class BigInt: IComparable, IComparable { //... public int CompareTo(int other)
{ //... } public int CompareTo(double other)code.google.com/p/hebmq
{ //... }
}
因为它实 IComparable 和 IComparable,所以可以和 int 和 double 进行比较,则可以如下使用:
BigInt bi = new BigInt(); bool b8 = bi.IsBetween(10, 20); bool b9 = bi.IsBetween(1.424E+12, 2.3675E+36);
( .Net 中已经有了大整数类型,请参见:BigInteger 结构,不过没有实现 IComparable 和 IComparable )
其它比较扩展code.google.com/p/hebmg
有了上面的 IsBetween 扩展,再写其它比较扩展就易如反掌了,比如下面几个:
LessThan LessOrEquals GreatOrEquals GreatThan
本文介绍了一种用于比较对象间大小关系的方法——IsBetween,并提供了示例代码。此外,还探讨了如何针对IComparable接口进行扩展,以便于对不同类型的对象进行比较。
1183

被折叠的 条评论
为什么被折叠?



