使用代码合同,可以将合同应用于接口。这是通过声明一个实现接口的抽象类来完成的。接口应使用标记,ContractClassAttribute合同定义(抽象类)应使用标记。ContractClassForAttribute
C#示例...
[ContractClass(typeof(MyInterfaceContract))]
public interface IMyInterface
{
string DoWork(string input);
}
//切勿继承此合同定义类
[ContractClassFor(typeof(IMyInterface))]
internal abstract class MyInterfaceContract : IMyInterface
{
private MyInterfaceContract() { }
public string DoWork(string input)
{
Contract.Requires(!string.IsNullOrEmpty(input));
Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));
throw new NotSupportedException();
}
}
public class MyInterfaceImplmentation : IMyInterface
{
public string DoWork(string input)
{
return input;
}
}静态分析结果...