c# - 将合约添加到接口(interface)实现

标签 c# interface contract

我知道我不能在接口(interface)实现上添加先决条件。我必须创建一个契约类,在其中定义界面所见元素的契约。

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

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

你应该能够在 Foo 中添加它,因为你添加的是 postcondition (Ensures) 而不是 前提条件(要求)。

您不能添加特定于实现的先决条件,因为这样调用者就无法知道他们是否会违反契约:

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

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

关于c# - 将合约添加到接口(interface)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1385485/

相关文章:

c# - 如何与 JavaScript 共享 C# 整数变量

c# - ASP.Net:文本框的文本更改事件的调用序列问题

c# - ASP.NET C# 在循环内打开多个模式弹出窗口,一个接一个

java - 关于核心java可序列化接口(interface)的简单查询

Java 可选参数化接口(interface)

wcf - WCF 中的服务契约是什么?

java - 比较法违反了它的一般契约。简单比较

c# - 防止 visual studio 将 setter 方法限制为内部

来自 DLL 的 Delphi 接口(interface)

c# - PACT .NET 消费者测试 : flexible length array