7

下面的代码给了我警告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 闭嘴。

我是否遗漏了一些东西来使这个编译没有警告?

4

2 回答 2

9

代码契约手册第 2.8 节明确指出它应该是一个抽象类:

这些工具期望合约类是抽象的,并实现它为其提供合约的接口。

于 2010-09-04T01:15:31.613 回答
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); 
  } 
}

合同类必须是抽象的。

于 2010-09-04T01:23:41.960 回答