如果我写这个:
public sealed class Foo
{
private int count;
private object owner;
private void Bar()
{
Contract.Requires(count > 0);
Contract.Ensures(owner == null || count > 0);
if (count == 1)
owner = null;
--count;
}
}
静态合约检查器可以证明所有断言。
但如果我改写这个:
public sealed class Foo
{
private int count;
private object owner;
private void Bar()
{
Contract.Requires(count > 0);
Contract.Ensures(owner == null || count > 0);
--count;
if (count == 0)
owner = null;
}
}
它声称后置条件owner == null || count > 0
未经证实。
我想我可以证明第二种形式不违反这个后置条件:
// { count > 0 } it's required
--count;
// { count == 0 || count > 0 } if it was 1, it's now zero, otherwise it's still greater than zero
if (count == 0)
{
// { count == 0 } the if condition is true
owner = null;
// { count == 0 && owner == null } assignment works
}
// { count == 0 && owner == null || count != 0 && count > 0 } either the if was entered or not
// { owner == null || count > 0 } we can assume a weaker postcondition
我的证明有问题吗?
我在证明中添加了断言作为Contract.Assert
对代码的调用,我得出的结论是,如果我只添加这个断言,它就可以证明后置条件:
--count;
Contract.Assert(count == 0 || count > 0)
if (count == 0)
owner = null;
但是,如果我现在将相同的断言更改为“更自然”的方式,它会失败:
--count;
Contract.Assert(count >= 0)
if (count == 0)
owner = null;
预计这两个断言是等价的,但静态检查器对它们的处理方式不同。
(顺便说一下,我使用的是 VS10 的 beta 2)