C# 扩展方法奇思妙用 - IsBetween 通

  人员生日 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值