Why can minValue == maxValue in Random.Next?

2019-07-16 00:01发布

http://msdn.microsoft.com/en-us/library/2dx6wyd4.aspx

Apparently maxValue is an exclusive upper bound. So Random.Next(2,3) will always return 2. Random.Next(2,2) will also always return 2. Why do you suppose they even allow the min to be equal to the max in this case? It's misleading!

标签: .net random
2条回答
贼婆χ
2楼-- · 2019-07-16 00:37

Looks like just a bit of poor design to me. I agree that maxValue should be strictly greater than minValue - and it should throw an ArgumentOutOfRangeException if they're equal.

There are a few aspects to Random which I dislike - for one thing, it would be really nice to have it properly pluggable (in a well-documented way) so that you could have a subclass using a cryptographically secure source. It's possible now, but you basically need to know too much about the implementation, and which methods call which other ones :(

The gotchas around creating a new Random instance each time you go round a loop, and the obvious "fix" (a static variable) not being thread-safe are other annoyances.

Basically, I'm not terribly surprised to see another little wart :(

查看更多
做自己的国王
3楼-- · 2019-07-16 00:42

It's just a convention, if somewhat misleading. You'd be able to construct such a scenario (where the output is the same every time) in any case. It's useful for selecting a random element of an array, for example:

var random = new Random();
var element = someArray[random.Next(0, someArray.Length)]; // Of course, the lower bound needn't be specified here.

Edit: Misunderstood your question! My guess is that it's either a) poor design or b) a convenience for when your two bounds will potentially be the same. I'd agree that it's unintuitive though.

查看更多
登录 后发表回答