什么是code合同在.NET 4.0中的实际使用情况?实际、情况、code、NET

2023-09-03 09:54:57 作者:遥不可及

为了充分理解和利用提供了新的.NET Framework 4.0的到来,新功能和增强功能的优势,我想获得的真实世界的的一个示例应用程序的< A HREF =htt​​p://msdn.microsoft.com/en-us/library/system.diagnostics.contracts.aspx> code合同的。

In order to fully understand and take advantage of the new features and enhancements provided with the coming of the new .NET Framework 4.0, I would like to get an example of real-world application of Code Contracts.

的任何人有应用此功能的一个很好的例子?的

我想获得一个code样品用简短的解释帮我拿起来与它运行。

I would like to get a code sample with a brief explanation to help me get up and running with it.

推荐答案

从The code合约用户手册:

合约让你的前preSS preconditions,后置条件和对象不变量在code运行时   检查,静态分析和文档。

Contracts allow you to express preconditions, postconditions and object invariants in your code for runtime checking, static analysis, and documentation.

code合同用于静态验证;想象一下,如果 - 在编译的时候 - 你抓到不仅语法错误,但也的的逻辑错误。这是静态的程序验证的愿景。

Code Contracts are used for static verification; imagine if - at compile time - you caught not only syntax errors but also logic errors. This is the vision of static program verification.

您可以使用合同(和静态验证),以减少测试成本......特别是回归测试。举个例子,假设我写一些code这满足了一些商务需求......但后来,性能需求的变化,而我需要优化。如果我先写一份合同,然后 - 当我的新的优化code被证实 - 如果它不再履行原合同,我会得到一个错误信息在我的IDE,就像如果我有一个编译时错误。这样一来,你会发现并解决的bug几乎立即,其成本远低于一轮测试。

You could use contracts (and static verification) to reduce the cost of testing... in particular regression testing. As an example, let's say I write some code which fulfills some business needs... but later, performance needs change, and I'm required to optimize. If I first write a contract, then - when my new optimized code is verified - if it no longer fulfills the original contract I'll get an error message in my IDE, just like if I had a compile time error. As a result, you find and resolve the bug almost immediately, which costs less than a round of testing.