为什么静态分析忽略双重<= 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或者我用<替换<=时,它会警告我违规。这种不正当行为仅限于doublefloat。我假设它与浮点值的精度有关。

它甚至当我制定这样的规定:

Contract.Requires<ArgumentException>(!(0 > value)); 

那是一个错误还是我做错了什么?

+0

只是出于兴趣,为什么你不会允许0作为有效值? – thumbmunkeys 2014-10-09 10:43:43

+0

我希望允许0作为有效值。合同应该确保每个值> = 0. – vlow 2014-10-09 10:48:22

+2

绝对有趣,我会尝试联系弗朗切斯科,https://visualstudiogallery.msdn.microsoft.com/1ec7db13-3363-46c9-851f-1ce455f66970 – 2014-10-09 11:40:08

我希望你可能错过了安装微软代码合同。

您可以从微软研究院下载Microsoft代码契约:http://research.microsoft.com/en-us/projects/contracts/

现在在你的项目属性,你会得到一个额外的标签,您可以设置运行时和静态检查。

+0

请参阅此处了解更多详情https://www.develop.com/csharpcodecontracts – Joseph 2014-10-27 08:59:49

+0

Joseph,我正确安装了Code Contracts。正如您在我的问题中所看到的,代码合同通常工作,并且在上述特定情况下无法工作。 – vlow 2015-01-15 00:32:17