代码之家  ›  专栏  ›  技术社区  ›  cedrou

将合同添加到接口实现

  •  3
  • cedrou  · 技术社区  · 15 年前

    我理解我不能在接口实现上添加前提条件。我必须创建一个契约类,在该类中,我在接口所看到的元素上定义契约。

    但在以下情况下,如何在接口定义级别上不知道的实现的内部状态上添加契约?

    [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);
    
        <...>
      }
    }
    
    1 回复  |  直到 15 年前
        1
  •  3
  •   Jon Skeet    15 年前

    不能-后置条件不适用于 IFoo ,因为它没有在 伊福 . 只能引用接口的成员(或它扩展的其他接口)。

    你应该能把它加进去 Foo 但是,因为你在添加 后置条件 ( Ensures )而不是 先决条件 ( Requires )

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

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

    基本上,合同不允许对调用者“不公平”——如果调用者违反了一个先决条件,那么它应该总是指示一个错误,而不是他们无法预测的错误。