那么 C#4.0 代码契约实际上有什么作用吗?

发布于 2024-09-03 00:05:08 字数 285 浏览 3 评论 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

若水般的淡然安静女子 2024-09-10 00:05:08

来自 MSDN 上的合同类页面

您必须使用二进制重写器
插入运行时执行
合同。否则,签订此类合同
正如 Contract.Ensures 方法可以
仅进行静态测试,不会
如果出现以下情况,则在运行时抛出异常
合同被违反。您可以下载
二进制重写器 CCRewrite 来自
MSDN DevLabs Web 上的代码合同
地点。 CCRewrite 带有 Visual
Studio 插件使您能够
激活运行时合约执行
从项目属性页面。这
二进制重写器和 Visual Studio
加载项不随 Visual Studio 一起提供
2010 或 Windows SDK。

From the Contract Class page at MSDN:

You must use a binary rewriter to
insert run-time enforcement of
contracts. Otherwise, contracts such
as the Contract.Ensures method can
only be tested statically and will not
throw exceptions during run time if a
contract is violated. You can download
the binary rewriter CCRewrite from
Code Contracts on the MSDN DevLabs Web
site. CCRewrite comes with a Visual
Studio add-in that enables you to
activate run-time contract enforcement
from the project Properties page. The
binary rewriter and the Visual Studio
add-in do not ship with Visual Studio
2010 or the Windows SDK.

暖伴 2024-09-10 00:05:08

扩展 JSBangs 的答案:

您必须在此处选中“执行运行时合同检查”框:

在此处输入图像描述

(我也选中“静态检查>执行静态合同检查”框)

Expanding on JSBangs' answer:

You must check the "Perform Runtime Contract Checking" box here:

enter image description here

(I also checked the "Static Checking > Peform Static Contract Checking" box)

温暖的光 2024-09-10 00:05:08

如果您希望 .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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文