代码合同:如何在后置条件中声明字段/属性的值未发生变化?

时间:2010-01-28 11:56:36

标签: c# .net code-contracts design-by-contract

我最好只用一个代码示例来展示我想要完成的任务?

class SomeClass
{
    public int SomeProperty;

    public void SomeOperation()
    {
        Contract.Ensures( "SomeProperty's value has not changed." );
                     //   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                     //    How can I write this post-condition?
    }
};

(传递给Contract.Ensures()的字符串当然只是真正的后置条件表达式的占位符。)

我该怎么做? Contract.OldValue<>()会在这里有用吗?

1 个答案:

答案 0 :(得分:5)

Contract.OldValue应该足够了:

Contract.Ensures(this.SomeProperty == Contract.OldValue(this.SomePropety));