Dot-Net

.net 中是否有代表“範圍”的標準類?

  • April 26, 2021

我們有很多程式碼,其中包含價格、利潤、成本等的“最小值”和“最大值”。目前,它們作為兩個參數傳遞給方法,並且通常具有不同的屬性/方法來檢索它們。

在過去的幾十年裡,我已經看到了 101 個自定義類來儲存不同程式碼庫中的值範圍,在我創建另一個這樣的類之前,我希望確認現在的 .NET 框架沒有內置這樣的類某處。

(如果需要,我知道如何創建自己的課程,但我們已經有太多的輪子了,我無法一時興起發明另一個)

AFAIK .NET 中沒有這樣的東西。不過,想出一個通用的實現會很有趣。

建構一個通用的 BCL 質量範圍類型需要做很多工作,但它可能看起來像這樣:

public enum RangeBoundaryType
{
   Inclusive = 0,
   Exclusive
}

public struct Range<T> : IComparable<Range<T>>, IEquatable<Range<T>>
   where T : struct, IComparable<T>
{
   public Range(T min, T max) : 
       this(min, RangeBoundaryType.Inclusive, 
           max, RangeBoundaryType.Inclusive)
   {
   }

   public Range(T min, RangeBoundaryType minBoundary,
       T max, RangeBoundaryType maxBoundary)
   {
       this.Min = min;
       this.Max = max;
       this.MinBoundary = minBoundary;
       this.MaxBoundary = maxBoundary;
   }

   public T Min { get; private set; }
   public T Max { get; private set; }
   public RangeBoundaryType MinBoundary { get; private set; }
   public RangeBoundaryType MaxBoundary { get; private set; }

   public bool Contains(Range<T> other)
   {
       // TODO
   }

   public bool OverlapsWith(Range<T> other)
   {
       // TODO
   }

   public override string ToString()
   {
       return string.Format("Min: {0} {1}, Max: {2} {3}",
           this.Min, this.MinBoundary, this.Max, this.MaxBoundary);
   }

   public override int GetHashCode()
   {
       return this.Min.GetHashCode() << 256 ^ this.Max.GetHashCode();
   }

   public bool Equals(Range<T> other)
   {
       return
           this.Min.CompareTo(other.Min) == 0 &&
           this.Max.CompareTo(other.Max) == 0 &&
           this.MinBoundary == other.MinBoundary &&
           this.MaxBoundary == other.MaxBoundary;
   }

   public static bool operator ==(Range<T> left, Range<T> right)
   {
       return left.Equals(right);
   }

   public static bool operator !=(Range<T> left, Range<T> right)
   {
       return !left.Equals(right);
   }

   public int CompareTo(Range<T> other)
   {
       if (this.Min.CompareTo(other.Min) != 0)
       {
           return this.Min.CompareTo(other.Min);
       }

       if (this.Max.CompareTo(other.Max) != 0)
       {
           this.Max.CompareTo(other.Max);
       }

       if (this.MinBoundary != other.MinBoundary)
       {
           return this.MinBoundary.CompareTo(other.Min);
       }

       if (this.MaxBoundary != other.MaxBoundary)
       {
           return this.MaxBoundary.CompareTo(other.MaxBoundary);
       }

       return 0;
   }
}

沒錯,在 2020 年之前,C# 或範圍的 BCL 中沒有內置類。但是,TimeSpanBCL 中有用於表示時間跨度的內容,您可以另外使用 a 組合DateTime來表示時間範圍。

引用自:https://stackoverflow.com/questions/10172800