检查 .NET 中的先决条件
我是“早期失败”策略的粉丝,并且想要检查方法参数是否具有正确的值。在Java中,我会使用类似 Guava:
checkArgument(count > 0, "must be positive: %s", count);
.NET 有类似的东西吗?
I'm a fan of the "fail early" strategy and want to check that methods params have correct values for example. In Java I'd use something like Guava:
checkArgument(count > 0, "must be positive: %s", count);
Is there something similar for .NET?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您想要做的是按合同设计。
您应该使用代码契约来定义契约,即类型\方法的先决条件、后置条件和不变量在 C# 中。
IMO 代码合约的最佳和最全面的覆盖是这里。
What you want to do is Design By Contract.
You should use Code Contracts for defining contracts i.e. Preconditions, post-conditions and invariants for your types\methods in C#.
IMO the best and most comprehensive coverage of code-contracts is here.
代码合同:http://msdn.microsoft.com/en-us/devlabs/dd491992< /a>
Code contracts: http://msdn.microsoft.com/en-us/devlabs/dd491992
代码合同仍然是标准 Visual Studio 安装的附加组件/不是其一部分,但它们确实允许您表达前置条件和后置条件以及对象不变量。
可以使用不同的选项来强制执行合同作为编译时或运行时检查(或两者)。
Code Contracts are still an add on/not part of the standard Visual Studio install, but they do allow you to express pre and post conditions and object invariants.
Different options are available for enforcing the contracts as compile-time or run-time checks (or both).
查看 CuttingEdge.Conditions。它允许您以流畅的方式编写前提条件,如下所示:
您需要 C# 3.0 或 VB.NET 9.0 以及 .NET 2.0 或更高版本来使用 CuttingEdge.Conditions。
Take a look at CuttingEdge.Conditions. It allows you to write your preconditions in a fluent manner, as follows:
You need C# 3.0 or VB.NET 9.0 with .NET 2.0 or up for CuttingEdge.Conditions.