C# 警惕超出范围的论点

C# 警惕超出范围的论点,c#,.net,generics,compare,numeric,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>,

我正在寻找一种方法来防止超出范围的争论,类似于

public static class Guard {

    public static void AgainstOutOfRange<TArgument>(TArgument argument,
        TArgument minInclusive, TArgument maxInclusive)
        where TArgument : struct, IComparable<TArgument>, IConvertible
    {
        if(argument.CompareTo ????
    }
公共静态类保护{
针对OutofRange的公共静态无效(target参数,
TArgument最小包含,TArgument最大包含)
其中targetment:struct,IComparable,IConvertible
{
如果(argument.CompareTo???)????
}
寻找泛型的“数字约束”,我在@Lee建议的地方苦苦思索

public static bool IsGreaterThan<T>(this T actual, T comp) where T : IComparable<T>
{
    return actual.CompareTo(comp) > 0;
}
public static bool大于(T实际值,T comp),其中T:i可比较
{
返回实际值。比较(comp)>0;
}
但是,我不确定这是否是包含性的、排他性的,以及如何检查“IsSmallerThan”(我还不完全理解
I可比较的

  • Inclusive意味着我们将把下限和上限作为有效值包含在内。例如,
    Guard.AgainstOutOfRange(5,0,5)
    应该接受
    5
    作为有效参数,因为我们允许
    0
    5
    Inclusive
  • 排他意味着我们要排除上下限。例如,
    Guard.ArgumentOutOfRange(5,0,5)
    应该拒绝将
    5
    作为有效参数,因为我们不允许上下限本身作为有效值
考虑到这一点,我认为您只是在寻找:

if(argument.CompareTo(minInclusive) < 0 ||
    argument.CompareTo(maxInclusive) > 0)
{
    throw new ArgumentException("Argument out of range");
}
然后我们会说,如果参数等于下限或上限,这也是一个无效参数

解释
实例的结果。比较到(obj)

小于零此实例按排序顺序位于obj之前

Zero:此实例发生在与obj排序顺序相同的位置

大于零:此实例按排序顺序跟随obj


你是否阅读了
IComparable
的文档?这是一个很好的开始理解它的方法,或者只是在谷歌上寻找信息。嘿,非常感谢你的详细解释。特别是最后一部分,它非常清晰。你的最新编辑肯定会对其他人有所帮助。
if(argument.CompareTo(minInclusive) <= 0 ||
    argument.CompareTo(maxInclusive) >= 0)
{
    throw new ArgumentException("Argument out of range");
}