gpt4 book ai didi

.net - .net 中是否有表示 “range” 的标准类?

转载 作者:行者123 更新时间:2023-12-04 13:33:50 24 4
gpt4 key购买 nike

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

在过去的几十年里,我已经看到 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;
}
}

关于.net - .net 中是否有表示 “range” 的标准类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10172800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com