Contract.Requires usage

拥有回忆 提交于 2019-11-29 22:51:09

You should do the following:

  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

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.

From the Contract class docs:

Important

You must install a Visual Studio add-in to enforce contracts. The Code Contracts Premium Edition add-in lets you specify static and run-time checking of code contracts on the project Properties page. If you do not enable run-time checking, contracts such as the Contract.Ensures method will not throw exceptions during run time if a contract is violated. The Visual Studio add-in does not ship with Visual Studio 2010 or the Windows SDK.

sgmoore

With a message like this it is usually helpful to specify exactly what you have done.

For example, you do not mention in the original message if you have installed the VS Addon, nor that you have enabled it under your project properties, or that you are actually running in debug vs release mode, etc.

Re Contract.Requires vs Contract.Requires<Exception>

Contract.Requires is recommended. According to the manual

If your code must throw a particular exception on failure of a particular precondition, you can use the generic overloaded form below. (Please read Section 5.1 before committing to this form in your code. You cannot use Requires < Exn <Exn>> without running the contract tools on all builds. If you do, you will get a runtime failure everytime.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!