我知道我不能在接口(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/