以下代码向我发出警告Contract class 'FooContracts' should be an abstract class
。从我在线阅读的所有示例(例如http://www.infoq.com/articles/code-contracts-csharp)中,这应该可行(大概没有编译器警告)。
[ContractClass(typeof(FooContracts))]
public interface IFoo {
void Bar(string foo);
}
[ContractClassFor(typeof(IFoo))]
internal sealed class FooContracts : IFoo {
void IFoo.Bar(string foo) {
Contract.Requires(foo != null);
}
}
我在Visual Studio 2010中,在项目属性的Code Contracts
部分中进行了以下设置:
Full
)Static Checking
下)我还定义了CONTRACTS_FULL
编译符号以使ReSharper闭嘴。
我是否遗漏了一些没有警告的编译?
答案 0 :(得分:9)
code contracts manual的第2.8节明确指出它应该是一个抽象类:
工具期望合同类是抽象的,并实现它提供合同的接口 对
答案 1 :(得分:3)
您引用的InfoQ文章很可能不正确。它基于深度C#的“早期访问”版本,因此代码契约实现可能在章节/文章最初编写和.NET 4发布之间发生了变化。
以下代码应该有效:
[ContractClass(typeof(FooContracts))]
public interface IFoo {
void Bar(string foo);
}
[ContractClassFor(typeof(IFoo))]
internal abstract class FooContracts : IFoo {
void IFoo.Bar(string foo) {
Contract.Requires(foo != null);
}
}
合同类必须是抽象的。