(也发布在 MSDN 论坛上- 但据我所知,这并没有获得太多流量。)
我一直在尝试提供Assert
and的示例Assume
。这是我得到的代码:
public static int RollDice(Random rng)
{
Contract.Ensures(Contract.Result<int>() >= 2 &&
Contract.Result<int>() <= 12);
if (rng == null)
{
rng = new Random();
}
Contract.Assert(rng != null);
int firstRoll = rng.Next(1, 7);
Contract.Assume(firstRoll >= 1 && firstRoll <= 6);
int secondRoll = rng.Next(1, 7);
Contract.Assume(secondRoll >= 1 && secondRoll <= 6);
return firstRoll + secondRoll;
}
(当然,能够传入空引用而不是现有Random
引用的业务纯粹是教学。)
我曾希望,如果检查员知道这一点firstRoll
并且secondRoll
每个人都在范围内[1, 6]
,那么它能够计算出总和在范围内[2, 12]
。
这是不合理的希望吗?我意识到这是一项棘手的工作,确切地计算出可能发生的事情......但我希望检查员足够聪明:)
如果现在不支持,这里有没有人知道它是否可能在不久的将来得到支持?
编辑:我现在发现静态检查器中有非常复杂的算术选项。使用“高级”文本框,我可以从 Visual Studio 中试用它们,但据我所知,它们的作用没有像样的解释。