如何正确使用代码契约?

How to use Code Contracts properly?

我从原始站点安装了代码合约并尝试编写一些示例代码。但是 R# 只是写 Method invocation is skipped。当我观看反编译的源代码时,我发现该方法是有条件的:必须定义 CONTRACTS_FULL 常量。我检查了项目设置中 Code Contracts 选项卡中的所有内容,但它似乎不起作用。

如何解决?

"Conditional constants"(更准确地说:"conditional compilation symbols")在项目属性的构建选项卡中设置(或定义)。

只需在 "Conditional compilation symbols" 文本字段中输入“CONTRACTS_FULL”,一切就绪。

user documentation(pdf) 是这样说的:

2 Contracts

Most methods of the contract class are conditionally compiled, meaning the compiler only emits calls to these methods when a special symbol, the full-contract symbol, is defined. That symbol is CONTRACTS_FULL. This allows writing contracts in your code without the use of #ifdef's, yet product different builds, some with contracts, and some without.

If you are using Visual Studio 2008 or later (Section 6) or msbuild (Section A.1), then you don't need to define this symbol yourself. Instead, when you use the provided UI to enable runtime or static checking (or properties in your projects or /p defines in msbuild arguments), the build automatically defines this symbol and performs the appropriate rewrite actions. If you use your own build mechanism, then you need to define the full-contract symbol if you want the contracts to be emitted into your assemblies for further consumption by tools.

因此,根据 CONTRACTS_FULL 的存在,有条件地编译代码契约方法。

如果您选中 Perform runtime contract checkingPerform static contract checking,则 Visual Studio 将确保 CONTRACTS_FULL 已定义,但作为传递给构建过程的参数而不是常量在项目中定义。因此,您只需选中这些框即可打开合同检查。 (另一种方法是让这些复选框导致在项目中定义 CONTRACTS_FULL 常量,但这样你就无法保持文本字段及其两个复选框同步。)

因此,就任何其他工具(包括 Resharper)而言,Contract 中的方法以未定义的常量为条件。您可以忽略警告或手动定义常量。