添加合同到接口实现 [英] Add contract to interface implementation

查看:105
本文介绍了添加合同到接口实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我不能在接口实现上添加前置条件。我必须创建一个契约类,我在其中定义接口所见元素的契约。

I understand that I cannot add preconditions on an interface implementation. I have to create a contract class where I define contracts on elements that are seen by the interface.

但在下面的例子中,如何在内部状态上添加契约因此在接口定义级别不知道的实现?

But in the following case, how can add a contract on an internal state of the implementation that is therefore not known at the interface definition level ?

[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 中声明。您只能引用接口的成员(或其扩展的其他接口)。

You can't - that postcondition isn't appropriate for all implementations of IFoo, because it's not declared in IFoo. You can only refer to members of the interface (or other interfaces it extends).

您应该能够在 Foo 但是,因为你要添加后置条件确保)而不是前置条件需要)。

You should be able to add it in Foo though, because you're adding a postcondition (Ensures) rather than a precondition (Requires).

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

You can't add an implementation-specific precondition because then a caller wouldn't be able to know whether or not they were going to violate the contract:

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

基本上,合约不允许对来电者不公平 - 如果调用者违反了一个前提条件,它应该始终指出一个错误而不是他们无法预测的错误。

Basically, contracts aren't allowed to be "unfair" to callers - if the caller violates a precondition, that should always indicate a bug rather than something they couldn't have predicted.

这篇关于添加合同到接口实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆