C# 中的代码契约和 null 检查
在我的代码中,我经常这样做:
myfunction (parameter p)
{
if(p == null)
return;
}
我如何用代码合约替换它?
我有兴趣找出是否已传入 null 并通过静态检查捕获它。
我感兴趣的是,如果在我们的测试期间传入 null,则抛出合同异常
对于生产,我想退出该函数。
代码合约能做到这一点吗?这对于代码合约来说是一个很好的用途吗?
In my code i do this a lot:
myfunction (parameter p)
{
if(p == null)
return;
}
How would I replace this with a code contract?
I'm interested in finding out if a null has been passed in and have it caught by static checking.
I'm interested in having a contract exception be thrown if null is passed in during our testing
For production I want to exit out of the function.
Can code contracts do this at all? Is this a good use for code contracts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
其语法是:
这需要位于方法的顶部。所有
Contract.Requires
(以及其他合约语句)必须位于方法中的所有其他语句之前。The syntax for this is:
This needs to be at the top of the method. All
Contract.Requires
(and other contract statements) must precede all other statements in the method.在研究我们的代码库的代码契约时偶然发现了这个问题。这里的答案是不完整的。发布此信息以供将来参考。
代码相当简单。用此行替换运行时空检查。这将引发 System.Diagnostics.Contracts.ContractException 类型的异常(显然您无法显式捕获该异常,除非您捕获所有异常;它不是设计为在运行时捕获的)。
您可以使用 Microsoft 插件进行代码契约静态分析,可在此处找到。
使用上面的以下内容:
或者,如果您想抛出不同的异常(例如
ArgumentNullException
),您可以可以执行以下操作:但是,这需要代码契约二进制重写器,它包含在 代码合约插件。
据我了解,在发布模式下构建项目将禁用代码契约检查(尽管您可以在项目属性中覆盖它)。所以是的,你可以这样做。
简短的回答 - 是的。
Stumbled across this question while researching code contracts for our codebase. The answers here are incomplete. Posting this for future reference.
The code is fairly simple. Replace your runtime null check with this line. This will throw an exception of type
System.Diagnostics.Contracts.ContractException
(which you apparently cannot catch explicitly, unless you catch all exceptions; it's not designed to be caught at runtime).You can use the Microsoft plugin for Code Contract static analysis, found here.
Use the following, from above:
Alternatively, if you want to throw a different exception (such as an
ArgumentNullException
) you can do the following:This, however, requires the Code Contracts Binary Rewriter, which is included with the Code Contract plugin.
From what I understand, building your project in Release mode will disable the Code Contract checking (although you can override this in your project properties). So yes, you can do this.
Short answer - Yes.
这些帖子此处和这里有很多很棒的选择。
编辑:我第一次误读了你的帖子,以为你抛出了 ArgumentNullException 或者其他什么东西,直到我看到 Jon Skeet 的评论。我绝对建议至少使用链接问题中提供的多种方法中的一种。
在此复制 John Feminella 的答案之一:
These posts here and here have a lot of great options.
Edit: I misread your post the first time, thinking you were throwing an ArgumentNullException or something, until I saw Jon Skeet's comment. I would definitely suggest using at least one of the many approaches provided in the linked questions.
Reproducing one of the answers by John Feminella here: