.NET 4.0 code合同。什么时候使用?当他们是在浪费时间?是在、什么时候、合同、时间

2023-09-04 00:06:07 作者:ガ綠魄

我一直在学习.NET 4.0 code合同,并期待在计算器以及在有关这个问题。

I have been studying .NET 4.0 Code Contracts and looking on stackoverflow as well at question regarding this.

我还从来没有遇到过使用code合同,这样得到我想知道......这是真正有用的任何样品code?或者,也许它唯一有用的你code达到一定的复杂性?任何人在那里使用code合同和真的很高兴他们做到了?

I still have never come across any sample code that uses code contracts so that gets me wondering.. is this really useful ? Or maybe its only useful one your code reaches a certain complexity? Anyone out there using Code Contracts and really glad they did?

在我看来,所有code合约都是在一个断言在发生什么,什么出去,增加了能够揣摩出入在编译时的值的方法..但随后这将需要更多的code在所有的方法..是值得吗?

Seems to me that all Code Contracts are is a Assertion on what goes in and what goes out of a method with the addition of being able to try to figure out the values going in and out at compile time... But then this is going to require more code on all your methods.. is it worth it ?

有一个好处我注意到的是,在我看来,你可以用一种code合同为单元测试的第一线......然后,当你写单元测试,以避免写一些,因为更基本的测试code合同覆盖它已经......是真的吗?

A benefit I noticed is it seems to me you can use code contracts kind of as a first line of unit testing... then when you write unit test to can avoid writing some of the more basic tests because the Code Contracts cover it already.. is that true ?

将合同与WCF电话的工作?我猜不是因为代理与你自动创建的,你不能改变。

Will contracts work with WCF calls? I am guessing not since a proxy is created with you automatically that you cant change.

推荐答案

我用它们每次我需要验证输入参数都需要有一个特定的值(数字为正数,对象不为null)。

I use them anytime i need to validate that an input parameter needs to have a specific value (number is positive, object is not null).

有关输出,我用它们只要我相信,一个返回值应该是在一定的状态(不为空的例子)。

For outputs, I use them anytime I am certain that a return value should be in a certain state (not null for example).

有在code合同确保了一个异常将被抛出了一个意外的价值作物的那一刻,并在code的,因为那里的对象可能会不小心将它留在损坏状态不会进一步下跌偶然的假设。

Having contracts in the code ensures that an exception will be thrown the moment that an unexpected value crops up, and not further down in the code where objects may accidentally be left in a corrupted state because of an accidental assumption.

我个人认为,它使codeA变得更干净。该符号使它少了很多写的(而不是使用if(... == NULL)...)。这种方式太 Contract.Requires 很前面的是什么,努力实现。当我看到,我知道,code正在评估一个参数是在一定的状态。

Personally, I think it makes the code a lot cleaner. The notation makes it a lot less to write (instead of using if(....== null)....). This way too Contract.Requires is very up front in what it is trying to accomplish. When I see that I know that the code is evaluating that a parameter is in a certain state.

 
精彩推荐