c# - 与 Contract.Requires<T> 相比抛出异常?

标签 c# exception error-handling code-contracts

我想知道我是应该抛出异常还是调用 Contract.Requires<TException>

例如:

public static void Function(String str)
{
    if (str == null) throw new ArgumentNullException("str", "Input string cannot be null.");

    // ...
}

对比

public static void Function(String str)
{
    Contract.Requires<ArgumentNullException>(str != null, "Input string cannot be null.");

    // ...
}

Contract.Requires<TException> 不需要 CONTRACTS_FULL符号我也可以将它保留在我的发布版本中。

这是我的考虑:

缺点:您不能调用自定义异常类型构造函数的重载版本。根本没有办法将额外的参数传递给构造函数。

Pro:静态工具支持(例如,通知调用者违反契约(Contract))。

我应该使用哪一个,在什么样的情况下使用?

最佳答案

if-then-throw 之间的基本权衡和 Requires<TException>如 CodeContract 用户指南中所述,您可以使用发布位进行构建。

情况 1:您只使用 if-then-throw , 没有 Requires<TException> .在这种情况下,您可以在不在 dll/exe 上运行契约(Contract)工具的情况下构建您的发布位。优点是构建速度更快,并且没有工具引入错误的风险。第二个优势是团队成员可以选择不使用 CodeContract 工具。缺点是您没有继承 requires 的合约,并且您的合约不一定对工具可见(除非您使用 EndContract )。您可以使用汇编模式指定这种情况:自定义参数验证

案例 2:您决定始终在您的发布位上运行 CodeContract 工具。这使您可以使用 Requires<TException>你得到契约的继承,包括接口(interface)的检测等。你的契约是干净的并且工具可识别。缺点是每个构建代码的人都必须安装 CodeContracts 工具。您可以在 Contract 属性 Pane 中使用装配模式:Standard 来指定这种情况。

希望这一切都清楚了。

关于c# - 与 Contract.Requires<T> 相比抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14991647/

相关文章:

c++ - C++ 中的 std::async 和 lambda 函数不提供关联状态

c++ - 'this' cannot be used in a constant expression error (C++)

c# - 如何在 C# 中创建多个对象?

java - 线程只运行一次

java - Java异常层次结构背后的基本原理

python-3.x - Python3 IndentationError : expected an indented block - should not throw this

r - 在group_by中调用cor函数的`The standard deviation is zero`错误

c# - 如何使用 CreateDocumentAsync 将 json 内容存储到 CosmosDB

c# - 如何使用 C# 客户端获取另一个应用程序中单击的 GUI 元素的信息?

c# - 使用多个正则表达式命令解析消息时的性能问题