Random.Next 代码合约是否不正确?
我安装了一个插件(Microsoft 的代码契约编辑器扩展),它显示 .NET 的所有代码契约。
当我查看 Random.Next
的合约时,它说 ensures result <= maxValue
而 MSDN 声明 maxValue 是独占的。合同不是应该说确保结果<<吗?最大值?
I've installed a plugin (Code Contract Editor Extensions by Microsoft) which displays all code contracts for .NET.
When I look at the contract for Random.Next
it says ensures result <= maxValue
while MSDN states that maxValue is exclusive. Shouldn't the contract say ensures result < maxValue
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它不是排他性的,MSDN 也没有声明它是排他性的。好吧,在谈论 maxValue 时,它确实使用了“独占”一词,这不太清楚,但现实是,在绝大多数情况下确实如预期的那样独家。
然而,也存在一些极端情况:具体举例来说,
Next(0)
返回0
;Next(4,4)
返回4
。当它没有选项时,它是包容性的,这记录在 MSDN 上的“返回值”部分中:引用
下一步(maxValue)
:以及来自
Next(minValue,maxValue)
:(当然也可以说“返回了
maxValue
”)因此,在这两种情况下,都可能返回
maxValue
。唯一的例外是无参数
Next()
,它被记录为严格< int.MaxValue
。It is not exclusive, and MSDN does not state that it is. Well, OK, it does use the word "exclusive" when talking about
maxValue
, which is less than clear, but the reality is that in the vast majority of cases it is indeed exclusive as expected.There are, however, some corner-cases: to be specific with examples,
Next(0)
returns0
;Next(4,4)
returns4
. It is inclusive when it has no option, and this is documented in the "Return Value" sections on MSDN:To quote from
Next(maxValue)
:and from
Next(minValue,maxValue)
:(which of course could also be stated "
maxValue
is returned")So in both cases, it is possible for
maxValue
to be returned.The only exception is the parameterless
Next()
which is documented as being strictly< int.MaxValue
.由于MSDN中的契约比代码契约使用的契约更严格,因此代码契约使用的契约显然是正确的,但也许不严格。
另一方面,如果您要在自己的
Random
派生类中提供Next
的自定义实现,它可能无法满足 MSDN 上指定的约定,但约定检查器获胜没有注意到这个错误。因此,微软仍然建议消除两个合同版本之间的差异。如果 MSDN 的行为最初是一个错误,然后他们更改了代码以适应规范,我不会感到惊讶。
我建议您提交 MS Connect 问题,要求他们改进其中一个。
引用 MSDN 的
Next()
Since the contract in MSDN is stricter than the contract used by code contracts, the contract used by code contracts is obviously correct, but perhaps not tight.
On the other hand if you were to supply a custom implementation of
Next
in your ownRandom
derived class, it might not fulfill the contract specified on MSDN, but the contract checker won't notice the mistake. So it's still advisable for MS to remove the discrepancy between the two contract versions.I wouldn't be surprised if the MSDN behavior was originally a mistake and they then changed the code to fit the specification.
I suggest that you file a MS Connect issue asking them to improve one of them.
Quoting MSDN for
Next()