Debug.Assert 与代码契约的使用 [英] Debug.Assert vs Code Contract usage

查看:27
本文介绍了Debug.Assert 与代码契约的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我什么时候应该对代码契约进行 debug.assert,反之亦然?我想检查一种方法的先决条件,我很困惑选择一个而不是另一个.我有单元测试,我想测试失败场景并期待异常.

When should I debug.assert over code contracts or vice versa? I want to check precondition for a method and I am confused to choose one over the other. I have unit tests where I want to test failure scenarios and expect exceptions.

在同一方法上使用 Debug.Assert 和 Code 契约是否是一个好习惯.如果是这样,代码的编写顺序是什么?

Is it a good practice to use Debug.Assert and Code contract on the same method. If so what would be the order in which the code should be written?

Debug.Assert(parameter!= null);
Contract.Requires<ArgumentNullException>(parameter != null, "parameter");

Contract.Requires<ArgumentNullException>(parameter != null, "parameter");
Debug.Assert(parameter!= null);

这背后有什么理由吗?

推荐答案

这些是不同的.调试断言仅在代码编译为调试时执行,因此只会在调试下检查/断言.这个想法是将它用于您正在开发的代码的健全性检查".代码契约可用于调试或发布.他们确保方法的前后条件符合方法的期望(满足合同).还有一个提供类似功能的测试框架,旨在检查测试合规性.

These are different things. A debug assert is only executed when the code is compiled as debug and therefore will only check/assert under debug. The idea is to use this for "sanity checks" for code you are developing. Code contracts can be used in either debug or release. They assure that pre and post conditions of methods comply with the expectations of the method (meet the contract). There is also a testing framework that provides similar functionality, designed for checking test compliance.

如果您想确保某些事情在开发代码时(以及在以后的维护开发中)符合您的预期,请使用 Debug.Assert.

Use Debug.Assert when you want ensure that certain things are as you expect when developing the code (and in later maintenance development).

当您想确保调试和发布中的条件都为真时,请使用代码契约.契约还允许某些形式的静态分析,这有助于验证您的程序是否正确".

Use code contracts when you want to assure that conditions are true in both debug and release. Contracts also allow certain forms of static analysis that can be helpful in verifying that your program is "correct".

在创建单元测试时使用测试框架断言.

Use the Testing framework assertions when creating unit tests.

这篇关于Debug.Assert 与代码契约的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆