在我们的项目中,我们定义了两个三个构建配置,Release、Debug 和“Debug-plus-contracts”。这些定义如下:
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
<DefineConstants>TRACE;DEBUG</DefineConstants>
<DebugType>full</DebugType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Debug-plus-contracts'">
<DefineConstants>TRACE;DEBUG;CONTRACTS_FULL</DefineConstants>
<CodeContractsEnableRuntimeChecking>True</CodeContractsEnableRuntimeChecking>
<CodeContractsRuntimeThrowOnFailure>False</CodeContractsRuntimeThrowOnFailure>
...
我们定义了两个调试配置,因为“Debug-plus-contracts”仅在具有 Code Contracts for .NET 的机器上构建安装
我的问题是,在每个配置中编译时,诸如 Contract.Requires(source.Any())
之类的行会发生什么情况?假设在运行时违反了,在哪些配置中会发生什么?
我问是因为我(在某处)听说在 Debug 配置中,Contract.Requires
被编译为 Debug.Assert
。但有证据表明这不是真的,我们有一些 Contract.Requires
在 Debug-plus 中失败但在 Debug 中没有。
最佳答案
Contract.Requires
声明为
[ConditionalAttribute("CONTRACTS_FULL")] public static void Requires( bool condition ) [ConditionalAttribute("CONTRACTS_FULL")] public static void Requires( bool condition, string userMessage )
这意味着如果 CONTRACTS_FULL
undefined symbol ,任何对 Requires
的调用将被编译器完全删除。根本不会执行检查。
如果您确实定义了 CONTRACTS_FULL
符号,但您没有在构建时安装代码契约(Contract)或不使用其重写器,任何对 Requires
的调用无论检查是否通过,都会抛出异常,告诉您没有代码契约重写器,它将无法工作。
注意:这不同于Contract.Requires<TException>
.后者没有相同的 ConditionalAttribute
,所以在任何配置中都会失败,除非使用代码契约重写器。
关于c# - Contract.Requires 在没有安装 Code Contracts 的情况下构建时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20540721/