代表百分比,概率或库存水平 [英] Representing a percentage, probability, or stock level
问题描述
.NET 3.5中是否有一种简洁的方法来表示有界数字值?
Is there a succinct way to represent a bounded numeric value in .NET 3.5?
通过这种方式,我表示的是诸如百分比(0-100)概率的值(0-1)或库存水平(0或更高)。
By this I mean a value such as a percentage (0 - 100) probability (0 - 1) or stock level (0 or above).
我想要 ArgumentOutOfRangeException
(或等价物) ),如果尝试了超出范围的分配。我还希望静态 MaxValue
和 MinValue
属性可用。
I would want a ArgumentOutOfRangeException
(or equivalent) to be thrown if an out-of-range assignment was attempted. I would also want static MaxValue
and MinValue
properties to be available.
在评论中建议另一个SO问题:这是结构
的很好用法。
推荐答案
我认为没有像Ada这样的内置方式范围关键字,但您可以轻松创建类似RestrictedRange< T>的类型。具有最小值和最大值以及当前值:
I don't think there is a built-in way like the Ada "range" keyword, but you could easily create a type like RestrictedRange<T> that had a min and max value along with the current value:
public class RestrictedRange<T> where T : IComparable
{
private T _Value;
public T MinValue { get; private set; }
public T MaxValue { get; private set; }
public RestrictedRange(T minValue, T maxValue)
: this(minValue, maxValue, minValue)
{
}
public RestrictedRange(T minValue, T maxValue, T value)
{
if (minValue.CompareTo(maxValue) > 0)
{
throw new ArgumentOutOfRangeException("minValue");
}
this.MinValue = minValue;
this.MaxValue = maxValue;
this.Value = value;
}
public T Value
{
get
{
return _Value;
}
set
{
if ((0 < MinValue.CompareTo(value)) || (MaxValue.CompareTo(value) < 0))
{
throw new ArgumentOutOfRangeException("value");
}
_Value = value;
}
}
public static implicit operator T(RestrictedRange<T> value)
{
return value.Value;
}
public override string ToString()
{
return MinValue + " <= " + Value + " <= " + MaxValue;
}
}
由于存在隐式转换,可以自动获取值,这将起作用:
Since there is an implicit conversion to automatically get the value, this will work:
var adultAge = new RestrictedRange<int>(18, 130, 21);
adultAge.Value++;
int currentAge = adultAge; // = 22
此外,您可以执行以下操作
In addition, you can do things like this
var stockLevel = new RestrictedRange<int>(0, 1000)
var percentage = new RestrictedRange<double>(0.0, 1.0);
这篇关于代表百分比,概率或库存水平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!