c# - 将方法参数验证代码重构为Contracts - 语句反转问题

标签 c# .net c#-4.0 code-contracts

旧的验证代码通常检查 bool 条件,如果条件为真则抛出异常。

相反,Contract.Requires(...) 做相反的事情(为了通过检查,我们需要否定旧条件)。

我正在重构旧代码,有时会看到一些相当高级的 bool 语句,反转它们并不是那么容易,只是做 Contract.Requires(!(*old statements*)) 看起来很糟糕并且非常困惑。

如果它有类似 Contract.RequiresNot() 的东西,重构在这里会更加清晰和直接。

我们也不能添加静态扩展方法。如果有人遇到这个问题并找到了一些好的解决方案,我很想听听。

最佳答案

您可以尝试保留旧的遗留验证并添加 Contract.EndContractBlock验证后立即调用。来自 MSDN:

Most code contains some parameter validation in the form of if-then-throw code. The contract tools recognize these statements as preconditions in the following cases:

When if-then-throw statements appear in this form, the tools recognize them as legacy requires statements. If no other contracts follow the if-then-throw sequence, end the code with the Contract.EndContractBlock method.

if ( x == null ) throw new ...
Contract.EndContractBlock(); // All previous "if" checks are preconditions

Note that the condition in the preceding test is a negated precondition. (The actual precondition would be x != null.) A negated precondition is highly restricted: It must be written as shown in the previous example; that is, it should contain no else clauses, and the body of the then clause must be a single throw statement. The if test is subject to both purity and visibility rules (see Usage Guidelines), but the throw expression is subject only to purity rules. However, the type of the exception thrown must be as visible as the method in which the contract occurs.

关于c# - 将方法参数验证代码重构为Contracts - 语句反转问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7382728/

相关文章:

c# - Visual Studio 2015 LinqToExcel 不工作

ASP.NET 如何从参数化 SQL 查询中删除双引号?

c# - GroupBox 中是否有任何属性指示已检查嵌套控件?

c# - Entity Framework Core - 如何提取有关底层 SQL 语法的详细信息?

c# - 使用另一个接口(interface)从一个接口(interface)实现泛型方法

wpf - 使用 WPF 和数据绑定(bind)将文件拖放到应用程序窗口中

c#-4.0 - 使用 C# 读取/编辑 XLIFF

c# - C#检测特定进程的CPU架构

c# - 寻找一个库来合成来自 soundfonts 的声音

c# - 需要 windows 安全性时下载文件的臭名昭著但尚未解决的问题