DateTime 的扩展方法如何制作一个流畅的界面(这些都是风靡一时的,对吧?)
public static class DateTimeTolerance
{
private static TimeSpan _defaultTolerance = TimeSpan.FromSeconds(10);
public static void SetDefault(TimeSpan tolerance)
{
_defaultTolerance = tolerance;
}
public static DateTimeWithin Within(this DateTime dateTime, TimeSpan tolerance)
{
return new DateTimeWithin(dateTime, tolerance);
}
public static DateTimeWithin Within(this DateTime dateTime)
{
return new DateTimeWithin(dateTime, _defaultTolerance);
}
}
这依赖于一个类来存储状态并为 == 和 != 定义几个运算符重载:
public class DateTimeWithin
{
public DateTimeWithin(DateTime dateTime, TimeSpan tolerance)
{
DateTime = dateTime;
Tolerance = tolerance;
}
public TimeSpan Tolerance { get; private set; }
public DateTime DateTime { get; private set; }
public static bool operator ==(DateTime lhs, DateTimeWithin rhs)
{
return (lhs - rhs.DateTime).Duration() <= rhs.Tolerance;
}
public static bool operator !=(DateTime lhs, DateTimeWithin rhs)
{
return (lhs - rhs.DateTime).Duration() > rhs.Tolerance;
}
public static bool operator ==(DateTimeWithin lhs, DateTime rhs)
{
return rhs == lhs;
}
public static bool operator !=(DateTimeWithin lhs, DateTime rhs)
{
return rhs != lhs;
}
}
然后在您的代码中,您可以执行以下操作:
DateTime d1 = DateTime.Now;
DateTime d2 = d1 + TimeSpan.FromSeconds(20);
if(d1 == d2.Within(TimeSpan.FromMinutes(1))) {
// TRUE! Do whatever
}
扩展类还包含一个默认的静态容差,以便您可以为整个项目设置容差并使用不带参数的 Within 方法:
DateTimeTolerance.SetDefault(TimeSpan.FromMinutes(1));
if(d1 == d2.Within()) { // Uses default tolerance
// TRUE! Do whatever
}
我有一些单元测试,但是在这里粘贴的代码有点太多了。