我有以下代码。
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(); // =)
}
在文档中我声明最小值和最大值必须在 [1-5] 范围内,并且最大值必须大于或等于最小值。
第三个异常是否构造正确?如果不是,我应该如何构造异常?
最佳答案
不,ArgumentOutOfRangeException
构造函数的参数应该始终是参数名称之一。您可以选择其中任何一个 - 我通常假设 earlier 参数是正确的,因此 later 参数相对于它是不正确的。不过,您可以(并且应该)在消息中提供更多信息。如果您提供实际值,它也真的很方便 - 所以:
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");
}
对于 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 + "]");
}
}
这样你就可以将上面的内容简化为:
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");
}
关于c# - 如何将 ArgumentOutOfRangeException 与多个参数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26025561/