防范超出范围的参数

时间:2014-10-06 20:49:35

标签: c# .net generics compare numeric

我正在寻找一种方法来防范超出范围的争论,这些都是......

public static class Guard {

    public static void AgainstOutOfRange<TArgument>(TArgument argument,
        TArgument minInclusive, TArgument maxInclusive)
        where TArgument : struct, IComparable<TArgument>, IConvertible
    {
        if(argument.CompareTo ????
    }

寻找数字约束&#39;关于泛型,我在@ this {@}建议

public static bool IsGreaterThan<T>(this T actual, T comp) where T : IComparable<T>
{
    return actual.CompareTo(comp) > 0;
}

但我不确定这是否具有包容性,排他性以及如何检查“IsSmallerThan&#39; (我还不完全理解IComparable

1 个答案:

答案 0 :(得分:2)

  • 包含意味着我们将包含下限和上限作为有效值。例如,Guard.AgainstOutOfRange(5, 0, 5)应接受5作为有效参数,因为我们允许0 5 包含
  • 独家意味着我们将排除下限和上限。例如,Guard.ArgumentOutOfRange(5, 0, 5)应该拒绝5作为有效参数,因为我们不允许上限和下限本身作为有效值。

考虑到这一点,我认为您只是在寻找:

if(argument.CompareTo(minInclusive) < 0 ||
    argument.CompareTo(maxInclusive) > 0)
{
    throw new ArgumentException("Argument out of range");
}

我们在这里说:

  • 如果将argumentminInclusive进行比较的结果小于零argument小于minInclusive)或
  • argumentmaxInclusive进行比较的结果是大于零argument大于maxInclusive

...然后我们有一个无效的论点。请注意,如果在任何一种情况下比较等于为零,我们将其视为有效参数(零不大于或小于零,因此它通过了我们的测试)。

如果我们要进行测试独占,我们可以在检查中包含CompareTo等于零的结果:

if(argument.CompareTo(minInclusive) <= 0 ||
    argument.CompareTo(maxInclusive) >= 0)
{
    throw new ArgumentException("Argument out of range");
}

然后我们说如果参数等于下限或上限,那也是一个无效的参数。

The documentation for IComparable.CompareTo解释了instance.CompareTo(obj)

的结果
  

小于零此实例在排序顺序中位于obj之前。

     

:此实例与obj在排序顺序中的位置相同。

     

大于零:此实例遵循排序顺序中的obj。

相关问题