那么 C#4.0 代码契约实际上有什么作用吗?
在阅读了受 Spec# 的影响的 System.Diagnostics.Contracts.Contract 静态类后,我感到非常兴奋,并立即开始在我的代码中调用 Contract.Requires() 和 Contract.Ensures()
。
我想这只是因为我的代码非常出色并且没有错误,所以直到最近才出现检查这些调用是否确实执行了某些操作。一个错误溜走了,我意识到这些调用没有做任何事情!我本以为他们至少会在违反条件时抛出异常,但没有这样的运气。
我错过了什么吗?有谁知道这到底是什么意思?
After reading about the System.Diagnostics.Contracts.Contract
static class that has been influenced by the awesomeness of Spec# I was thrilled and immediately started peppering my code with calls to Contract.Requires()
and Contract.Ensures()
.
I guess it's just because my code is so super-awesome and bug-free that checking that those calls actually did something just didn't come up until recently. A bug slipped through and I came to the realization that these calls do not do anything! I would have thought that they at least throw an exception when the condition is violated but no such luck.
Am I missing something? Does anyone know what the heck is the point?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 MSDN 上的合同类页面:
From the Contract Class page at MSDN:
扩展 JSBangs 的答案:
您必须在此处选中“执行运行时合同检查”框:
(我也选中“静态检查>执行静态合同检查”框)
Expanding on JSBangs' answer:
You must check the "Perform Runtime Contract Checking" box here:
(I also checked the "Static Checking > Peform Static Contract Checking" box)
如果您希望
.Requires
调用引发错误,您需要在项目设置中设置一个选项或使用.Requires
调用If you want the
.Requires
call to throw an error you need to set an option in project settings or use.Requires<T>
call