合同添加接口实现

我了解我无法在接口实现上添加前提条件.我必须创建一个合同类,在该类中我对接口所看到的元素定义合同.

但是在以下情况下,如何在实现的内部状态上添加一个因此在接口定义级别未知的协定?

[ContractClass(typeof(IFooContract))]
interface IFoo
{
  void Do(IBar bar);
}

[ContractClassFor(typeof(IFoo))]
sealed class IFooContract : IFoo
{
  void IFoo.Do(IBar bar)
  {
    Contract.Require (bar != null);

    // ERROR: unknown property
    //Contract.Require (MyState != null);
  }
}

class Foo : IFoo
{
  // The internal state that must not be null when Do(bar) is called.
  public object MyState { get; set; }

  void IFoo.Do(IBar bar)
  {
    // ERROR: cannot add precondition
    //Contract.Require (MyState != null);

    <...>
  }
}

解决方法:

您不能-后置条件不适用于IFoo的所有实现,因为它不是在IFoo中声明的.您只能引用该接口(或其扩展的其他接口)的成员.

不过,您应该能够在Foo中添加它,因为您要添加后置条件(确保)而不是前置条件(需要).

您不能添加特定于实现的前提条件,因为调用者将无法知道他们是否违反合同:

public void DoSomething(IFoo foo)
{
    // Is this valid or not? I have no way of telling.
    foo.Do(bar);
}

基本上,合同不允许对调用者“不公平”-如果调用者违反了前提条件,则应始终指示错误而不是他们无法预料的错误.

上一篇:双字段重复的数据,如何使用sql删除一个


下一篇:TIJ读书笔记08-数组的初始化和可变长参数形参