3

我了解我无法在接口实现上添加先决条件。我必须创建一个合同类,在其中定义界面可见的元素的合同。

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

[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);

    <...>
  }
}
4

1 回答 1

3

你不能——那个后置条件并不适合所有的实现IFoo,因为它没有在IFoo. 您只能引用接口的成员(或它扩展的其他接口)。

不过,您应该可以添加它Foo,因为您添加的是后置条件( Ensures) 而不是前置条件( Requires)。

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

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

基本上,合同不允许对调用者“不公平”——如果调用者违反了先决条件,那应该总是表明存在错误,而不是他们无法预测的事情。

于 2009-09-06T11:53:05.983 回答