开发者

Why can minValue == maxValue in Random.Next?

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!


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 :(


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜