Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

c# - Contract.Requires usage

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");
} 

I now have:

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

EDIT: I am working under VS2010 on debug mode.

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

The MSDN documentation says:

Specifies a precondition contract for the enclosing method or property.

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...