是否有标准类来表示.net中的"范围"?

Ian*_*ose 6 .net design-patterns range

我们有许多代码具有"最小"和"最大"值,用于价格,利润,成本等等.目前,这些代码作为两个参数传递给方法,并且通常具有不同的属性/方法来检索它们.

在我创建另一个这样的类之前,我已经看到了101个自定义类来存储不同代码库中的值范围,我希望确认.NET框架现在没有内置这样的类某处.

(我知道如果需要的话,如何创建我自己的课程,但是我已经在这个世界上拥有太多的轮子,只能随心所欲地发明一个)

jas*_*son 6

这是正确的,C#中没有内置类,范围内没有BCL.但是,TimeSpan在BCL中有表示时间跨度,您可以另外用a DateTime来表示时间跨度.

  • @Arman McHitaryan:不,那根本不是一回事。 (2认同)

Ste*_*ven 6

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;
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 2

这只是在 .Net Core 3.0 中发生了变化,请参阅System.Range
C# 8 还提供创建范围的语言支持

另请参阅“ c# 8 中的范围和索引类型是什么? ”Stackoverflow 问题。

请注意,这些仅支持整数范围,不支持双精度或浮点数范围。