通常,当我想检查构造函数参数是否已初始化时,我会这样做:
public MyCtor(MyObj obj) {
if(obj == null)
throw new ArgumentNullException("obj");
}
但是最近我偶然发现了 System.Diagnostics 命名空间中的这个不错的功能:
Contract.Requires<ArgumentNullException>(condition);
这有同样的效果吗?使用合约来验证参数有什么缺点吗?
最佳答案
是的,除非:
You must turn on run-time checking to use the Requires method.
(来自 MSDN)。如何打开它的说明必须在某处 here .
替代方案是CuttingEdge.Conditions
:
Condition.Requires(obj).IsNotNull();
Condition.Requires(myIntValue).IsGreaterThan(0);
Condition.Requries(myString).IsNotNullOrWhitespace();
更多关于codeplex .
这做同样的工作,但语法更简单,更易于阅读(在我看来) - 所以没有缺点(但请记住:它是基于意见的)。自从我发现以来就使用它:)
关于c# - 用契约(Contract)验证传递的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25664052/