相关疑难解决方法(0)

抛出异常与Contract.Requires <T>?

我想知道我是应该抛出异常还是打电话 Contract.Requires<TException>

例如:

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

    // ...
}
Run Code Online (Sandbox Code Playgroud)

VS

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

    // ...
}
Run Code Online (Sandbox Code Playgroud)

由于Contract.Requires<TException>不需要CONTRACTS_FULL符号,我可以将其保留在我的发布版本中.

这是我的考虑:

Con:您无法调用自定义异常类型构造函数的重载版本.根本无法将其他参数传递给构造函数.

Pro:静态工具支持(例如通知调用者违反合同).

我应该使用哪一种,以及哪种情况?

c# error-handling exception code-contracts

17
推荐指数
1
解决办法
6542
查看次数

标签 统计

c# ×1

code-contracts ×1

error-handling ×1

exception ×1