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

将合同添加到接口实现中

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

    我明白我不能在接口实现上添加先决条件。我必须创建一个契约类,在其中定义接口所看到的元素的契约。

    [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 回复  |  直到 16 年前
        1
  •  3
  •   Jon Skeet    16 年前

    IFoo ,因为它没有在 IFoo 。您只能引用接口(或其扩展的其他接口)的成员。

    Foo 后置条件 ( Ensures ( Requires ).

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

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

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