为什么静态分析忽略双重<= and > =要求?
问题描述:
我有利用.NET代码契约一个非常简单的类:为什么静态分析忽略双重<= and > =要求?
public class ContractSquareRoot
{
/// <summary>
/// Makes your life much easier by calling Math.Sqrt for you. Ain't that peachy.
/// </summary>
/// <param name="value">The value to calculate the square root from. No negatives!</param>
/// <returns>The square root of the given value. Obviously always > 0.</returns>
public double CalculateSquareRoot(double value)
{
Contract.Requires<ArgumentException>(0 <= value);
Contract.Ensures(0 <= Contract.Result<double>());
double squareRoot = Math.Sqrt(value);
return squareRoot;
}
}
当我打电话与负值的方法,我预计静态代码分析警告我一下吧。
class Program
{
static void Main(string[] args)
{
var barMansSquareroot = new ContractSquareRoot();
// This should not be possible...
barMansSquareroot.CalculateSquareRoot(-42);
}
}
但即使Contract.Requires
失败抛出所需的异常,静态代码分析标志着一切论断是正确的。有趣的是,当我将值类型更改为int
或者我用<
替换<=
时,它会警告我违规。这种不正当行为仅限于double
和float
。我假设它与浮点值的精度有关。
它甚至当我制定这样的规定:
Contract.Requires<ArgumentException>(!(0 > value));
那是一个错误还是我做错了什么?
答
我希望你可能错过了安装微软代码合同。
您可以从微软研究院下载Microsoft代码契约:http://research.microsoft.com/en-us/projects/contracts/
现在在你的项目属性,你会得到一个额外的标签,您可以设置运行时和静态检查。
只是出于兴趣,为什么你不会允许0作为有效值? – thumbmunkeys 2014-10-09 10:43:43
我希望允许0作为有效值。合同应该确保每个值> = 0. – vlow 2014-10-09 10:48:22
绝对有趣,我会尝试联系弗朗切斯科,https://visualstudiogallery.msdn.microsoft.com/1ec7db13-3363-46c9-851f-1ce455f66970 – 2014-10-09 11:40:08