7

価格、利益、コストなどの「最小」値と「最大」値を持つ多くのコードがあります。現在、これらは 2 つのパラメーターとしてメソッドに渡され、多くの場合、それらを取得するために異なるプロパティ/メソッドを持っています。

過去数十年にわたって、さまざまなコード ベースに値の範囲を格納する 101 個のカスタム クラスを見てきましたが、そのようなクラスをさらに作成する前に、最近の .NET フレームワークにそのようなクラスが組み込まれていないことを確認したいと思います。どこか。

(必要に応じて独自のクラスを作成する方法は知っていますが、この世界にはすでに車輪が多すぎて、気まぐれで別のものを発明することはできません)

4

4 に答える 4

6

私の知る限り、.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;
    }
}
于 2012-04-16T12:38:42.597 に答える
6

その通りです。2020 年より前は、C# または範囲用の BCL に組み込みクラスはありませんでした。ただし、TimeSpanBCL にはタイム スパンを表すための があり、これを で追加して構成し、DateTime時間の範囲を表すことができます。

于 2012-04-16T10:57:35.913 に答える