关于design by contract
最近想看看design by contract,但是ensure和require总是调不出来,希望有高手指点一下啊
using System;
using System.Diagnostics.Contracts;
public class RationalNumber
{
private int numberator;
private int denominator;
public RationalNumber(int numberator, int denominator)
{
Contract.Requires(denominator != 0, "The second argument can not be zero.");
//我理解如果分母不是0的话,应该报错啊
this.numberator = numberator;
this.denominator = denominator;
}
public int Denominator
{
get
{
Contract.Ensures(Contract.Result<int>() != 0);//同理,也应该报错
return this.denominator;
}
}
[ContractInvariantMethod]
protected void ObjectInvariant()
{
Contract.Invariant(this.denominator != 0);
}
}
public class SimpleCalculator
{
private static RationalNumber z;
public static void Main()
{
int x;
z=new RationalNumber(0,0) ;
Console.WriteLine(z.Denominator);
x = 3;
x++;
Contract.Assert(x == 4);
}
}
------解决方案--------------------
你用Release编译运行?
用Debug编译将给你错误信息。Contract.Ensures需要
下载安装Code Contract插件:
http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx