如何使用多个参数的ArgumentOutOfRangeException?

Gui*_*tre 5 c# exception

我有以下代码.

DoSomething(int min, int max)
{
    if (min < 1 || min > 5)
        throw new ArgumentOutOfRangeException("min");
    if (max < 1 || max > 5)
        throw new ArgumentOutOfRangeException("max");
    if (min > max)
        throw new ArgumentOutOfRangeException("min & max");

    DoSomethingWithYourLife(); // =)
}
Run Code Online (Sandbox Code Playgroud)

在文档中我声明min和max必须在[1-5]范围内,max必须大于或等于min.

第三个异常是否正确构建?如果没有,我应该如何构建异常?

Jon*_*eet 5

不,ArgumentOutOfRangeException构造函数的参数应始终是参数名称之一.你可以选择其中任何一个 - 我通常认为前面的参数是正确的,所以后面的参数与它相关是不正确的.您可以(并且应该)在消息中提供更多信息.如果给出实际值,它也非常方便 - 所以:

if (min < 1 || min > 5)
{
    throw new ArgumentOutOfRangeException("min", min, "min must be between 1 and 5 inclusive");
}
if (max < 1 || max > 5)
{
    throw new ArgumentOutOfRangeException("max", max, "max must be between 1 and 5 inclusive");
}
if (max < min)
{
    throw new ArgumentOutOfRangeException("max", max, "max must not not be less than min");
}
Run Code Online (Sandbox Code Playgroud)

对于Noda Time,我有这方面的帮助方法,例如:

internal static void CheckArgumentRange(string paramName,
    int value, int minInclusive, int maxInclusive)
{
    if (value < minInclusive || value > maxInclusive)
    {
        throw new ArgumentOutOfRangeException(paramName, value,
            "Value should be in range [" + minInclusive + "-" + maxInclusive + "]");
    }
}
Run Code Online (Sandbox Code Playgroud)

这样你可以简化以上内容:

Preconditions.CheckArgumentRange("min", min, 1, 5);
Preconditions.CheckArgumentRange("max", max, 1, 5);
if (max < min)
{
    throw new ArgumentOutOfRangeException("max", max, "max must not not be less than min");
}
Run Code Online (Sandbox Code Playgroud)