Làm thế nào về một phương pháp mở rộng cho DateTime để thực hiện một chút của một giao diện thông thạo (đó là tất cả các cơn giận dữ phải không?)
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);
}
}
này dựa vào một lớp học để lưu trữ nhà nước và xác định một ! quá tải vài nhà điều hành cho == và =:
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;
}
}
Sau đó trong mã của bạn, bạn có thể làm:
DateTime d1 = DateTime.Now;
DateTime d2 = d1 + TimeSpan.FromSeconds(20);
if(d1 == d2.Within(TimeSpan.FromMinutes(1))) {
// TRUE! Do whatever
}
Lớp mở rộng còn sở hữu một khoan dung tĩnh mặc định để bạn có thể thiết lập một sự khoan dung cho toàn bộ dự án của bạn và sử dụng Trong phương pháp không có tham số:
DateTimeTolerance.SetDefault(TimeSpan.FromMinutes(1));
if(d1 == d2.Within()) { // Uses default tolerance
// TRUE! Do whatever
}
Tôi có một vài đơn vị xét nghiệm nhưng mà muốn được một chút quá nhiều mã để dán ở đây.
Một cách hơi khác nhau: if ((date1 - date2) .TotalSeconds> 10) – Thomas
Điều này sẽ là '(dateTime1 - dateTime2) .Duration()
Marius