合同.需要使用 [英] Contract.Requires usage

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

问题描述

这是我的问题.我是合同设计的忠实拥护者,我正在使用这个概念,尤其是在开发可被其他开发人员使用的库时.我刚刚发现了一种新的执行方法,它是:Contract.Requires而不是Exception: 所以不用:

Here is my problem. I am a very big fan of Design by contract, I am using this concept especially when developing libraries that can be used by other developers. I just found out a new way of doing this which is: Contract.Requires instead of Exception: So instead of having:

public void SomeMethod(string name){
   if(name==null) throw new NullArgumentException("Null values not supported");
} 

我现在有:

public void SomeMethod(string name){
   Contract.Requires(name != null);
}

编辑:我正在VS2010下以调试模式工作.

EDIT: I am working under VS2010 on debug mode.

问题:即使namenullContract.Requires也不执行任何操作!

Problem: Contract.Requires does not do anything, even when name is null!

MSDN 文档说:

指定封闭方法的前提条件合同,或 属性.

Specifies a precondition contract for the enclosing method or property.

但是如果不满足条件,则什么也没有指定!

But nothing is specified in case the condition is not met!

我还注意到还有其他 Contract.Requires重载会引发异常,显示消息...但是Contract.Requires(Boolean)的作用是什么?

I also noticed there are other Contract.Requires overloads that throw exception, display message... but then what is Contract.Requires(Boolean) for?

编辑下面的回答突出显示必须安装插件才能具有Contract API的全部功能,但是对于希望其代码在不同平台上表现相同的Mono用户又该怎么办?

EDIT Answer below highlighted that a plug-in must be installed to have the full power of Contract API but then what about Mono users who want their code to behave the same on different platforms?

推荐答案

您应该执行以下操作:

  1. 按照nfechner的说明安装代码合同加载项
  2. 转到项目属性的代码合同"文件夹
  3. 选中执行运行时合同检查"
  4. 将组装模式"切换为标准合同要求"
  5. Contract.Requires<SomeException>替换Contract.Requires(第一个抛出System.Diagnostics.ContractException,第二个抛出您指定的对公共方法很重要的异常)
  1. Install the Code Contracts add-in as nfechner has noted
  2. Go to the project properties, 'Code Contracts' folder
  3. Check 'Perform Runtime Contract Checking'
  4. Switch 'Assembly Mode' to 'Standard Contract Requires'
  5. Substitute your Contract.Requires with Contract.Requires<SomeException> (the first one throws System.Diagnostics.ContractException while the second throws the exception you specified which is important for public methods)

这是基本设置.要获得更准确的配置,请参考手册

That's the basic setup. For more accurate configuration, refer to the manual

如果您使用Mono,则Contract类可能为空.我还没有这样做,但是《合同》手册的第七章似乎解释了如何提供自己的实现.

If you use Mono, probably, Contract class is empty. I haven't done this, but chapter seven from the Contracts manual seems to explain how to provide your own implementation.

这篇关于合同.需要使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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