[英]'maxValue' must be greater than zero
I'm not sure it's an issue, but something looks like not correct in the message. 我不确定这是一个问题,但是消息中似乎有些不正确 。
My first try: 我的第一次尝试:
try
{
var r = new Random();
Console.WriteLine(r.Next(-1));
}
catch (Exception e)
{
Console.WriteLine(e.GetType().ToString());
Console.WriteLine(e.Message);
}
Output: 输出:
System.ArgumentOutOfRangeException System.ArgumentOutOfRangeException
'maxValue' must be greater than zero. “ maxValue”必须大于零。
Parameter name: maxValue 参数名称:maxValue
My second try: 我的第二次尝试:
try
{
var r = new Random();
Console.WriteLine(r.Next(0));
}
catch (Exception e)
{
Console.WriteLine(e.GetType().ToString());
Console.WriteLine(e.Message);
}
Output: 输出:
0 0
So, the problem is: why is 0
greater than zero ? 因此, 问题是:为什么0
大于零 ?
If you take a look at the source code : 如果您看一下源代码 :
/*=====================================Next=====================================
**Returns: An int [0..maxValue)
**Arguments: maxValue -- One more than the greatest legal return value.
**Exceptions: None.
==============================================================================*/
public virtual int Next(int maxValue) {
if (maxValue<0) {
throw new ArgumentOutOfRangeException("maxValue", Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", "maxValue"));
}
Contract.EndContractBlock();
return (int)(Sample()*maxValue);
}
The value must be positive and zero is positive. 该值必须为正,零为正。
By definition from MSDN Random.Next Method (Int32) . 根据MSDN Random.Next方法(Int32)的定义。
maxValue Type: System.Int32 The exclusive upper bound of the random number to be generated. maxValue类型:System.Int32要生成的随机数的互斥上限。 maxValue must be greater than or equal to 0. maxValue必须大于或等于0。
So yes we can say that the error message is misleading. 所以可以,我们可以说该错误消息具有误导性。 It should be greater than or equal to zero. 它应该大于或等于零。
Random.Next Method (Int32) Random.Next方法(Int32)
maxValue: The exclusive upper bound of the random number to be generated. maxValue:要生成的随机数的排他上限。 maxValue must be greater than or equal to 0. maxValue必须大于或等于0。
Parameters 参数
maxValue
Type: System.Int32
The exclusive upper bound of the random number to be generated. 类型: System.Int32
要生成的随机数的排他上限。 maxValue must be greater than or equal to 0. maxValue必须大于或等于0。
该值不能为负。零或更高是可接受的,这就是为什么您超出答案的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.