Is there an interface in C# for interval

I'm making an interval collection extension of the famous C# library C5. The IInterval interface defines an interval with comparable endpoints (irrelevant members removed):

public interface IInterval<T> where T : IComparable<T>
{
    T Low { get; }
    T High { get; }
}

This works well in general, since interval endpoints can be anything comparable like integers, dates, or even strings.

However, it is sometimes favorable to be able to calculate the duration of an interval. The interval [3:5) has a duration of 2, and the interval [1PM, 9PM) has a duration of 8 hours. This is not possible with comparables, since it only gives us the order of elements, not their distance, eg it is difficult to give the distance between two strings. The endpoint type basically has to be interval-scaled values.

Is there an interface like IComparable<T> , that allows me to compare endpoints in general, but also do stuff like subtracting two endpoints to get a duration, and adding a duration to a low endpoint to get the high endpoint that could be used for an inheriting interface, IDurationInterval<T> : IInterval<T> for instance?

Or more concise: is there an interface for interval-scaled values?


No such interface exists. Some languages, like Scala, have abstractions over these kinds of operations, but .NET has none. Also, I've found that the .NET library designers are fairly conservative when it comes to adding levels of abstraction: it seems they tend to prefer simple and concrete over complex and abstract. They've never added this abstraction presumably because there's never been a pressing need for it in any of the .NET Framework's libraries. Also, it's an abstraction that can cause a lot of overhead if used improperly.

However, nothing in .NET's type system precludes such an interface. It would need two type parameters instead of one: one for the implementing type, and one of the result type. The most basic interface might look like this:

interface IAlgebraic<T, R> {
  T Add(R value)
  R Subtract(T value)
}

Unfortunately, there's no way to add this interface to existing types, like Int32 and DateTime. For those types, you'd need a corollary to IComparable<T> 's Comparer<T> .

interface IAlgebraicOps<T, R> {
  T Add(T x, R y)
  R Subtract(T x, T y)
}
链接地址: http://www.djcxy.com/p/86654.html

上一篇: 如何避免自定义Java异常类中的重复

下一篇: C#中是否有一个用于间隔的接口?