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
'maxValue' must be greater than zero.
Parameter name: 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
So, the problem is: why is 0
greater than zero ?
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) .
maxValue Type: System.Int32 The exclusive upper bound of the random number to be generated. maxValue must be greater than or equal to 0.
So yes we can say that the error message is misleading. It should be greater than or equal to zero.
maxValue: The exclusive upper bound of the random number to be generated. maxValue must be greater than or equal to 0.
Parameters
maxValue
Type: System.Int32
The exclusive upper bound of the random number to be generated. maxValue must be greater than or equal to 0.
该值不能为负。零或更高是可接受的,这就是为什么您超出答案的原因。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.