I have the following code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(SqrtRoot(0));
Console.WriteLine(SqrtRoot(10));
Console.WriteLine(SqrtRoot(-10));
Console.ReadKey();
}
public static int SqrtRoot(int i)
{
Contract.Requires(i >= 0);
return (int)Math.Sqrt(i);
}
}
I am running it in debug mode, and it should fire some kind of error in the last line
Console.WriteLine(SqrtRoot(-10));
altough, for some reason, it doesn't. It seems to ignore the Contract.Requires() call. Should I set up something when trying to use Code Contracts?
开发者_运维知识库I'm using Visual Studio 2010 RC.
Thanks
You need to install the Visual Studio integration. While the CodeContracts library itself is part of .NET 4, your code needs to be rewritten by the Code Contracts rewriter (ccrewrite
) to actually use the library properly.
Download the installer from the DevLabs site.
I don't have that tab either but I found a workaround:
Contract.Requires<ArgumentOutOfRangeException>(i >= 0);
Probably the code contracts package must be installed but the download link is not working. http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx
I think you have to enable runtime contract checking in the project settings (there should be a "Code Contracts" pane...)
See the user documentation (section 6) for further information.
精彩评论