为什么静态分析会忽略double <=和> = require?

vlo*_*low 12 c# code-contracts

我有一个非常简单的类使用.NET代码合同:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我用负值调用方法时,我希望静态代码分析能够警告我.

class Program
{
    static void Main(string[] args)
    {

        var barMansSquareroot = new ContractSquareRoot();

        // This should not be possible...
        barMansSquareroot.CalculateSquareRoot(-42);

    }
}
Run Code Online (Sandbox Code Playgroud)

但即使Contract.Requires未能抛出所需的异常,静态代码分析也会将每个断言标记为正确.有趣的是,它提醒我关于违反当我改变的值类型int,或者如果我更换<=<.不良行为仅限于doublefloat.我假设它与浮点值的精度有关.

它甚至可以在我制定这样的要求时起作用:

Contract.Requires<ArgumentException>(!(0 > value));
Run Code Online (Sandbox Code Playgroud)

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

Jos*_*eph 1

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

您可以从 Microsoft Research 下载 Microsoft 代码合同:http://research.microsoft.com/en-us/projects/contracts/

现在,在您的项目属性上,您将获得一个额外的选项卡,您可以在其中设置运行时和静态检查。