c# – 如何正确使用代码合同?
作者:互联网
我从原始站点安装了代码合同,并尝试编写一些示例代码.但是R#只是写了跳过方法调用.当我看反编译的源时,我看到该方法是有条件的:必须定义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的存在而有条件地编译的.
如果检查执行运行时合同检查或执行静态合同检查,则Visual Studio将确保定义CONTRACTS_FULL,但作为参数传递给构建过程而不是项目中定义的常量.因此,您需要检查这些框以打开合同检查. (替代方法是使那些复选框导致在项目中定义CONTRACTS_FULL常量,但是在保持文本字段及其两个复选框保持同步时会遇到问题.)
因此,就任何其他工具(包括Resharper)而言,Contract中的方法是以未定义的常量为条件的.您可以忽略警告或手动定义常量.
标签:c,net,visual-studio-2015,code-contracts 来源: https://codeday.me/bug/20190623/1270590.html