Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么静态分析忽略双重<;=和>;=要求_C#_Code Contracts - Fatal编程技术网

C# 为什么静态分析忽略双重<;=和>;=要求

C# 为什么静态分析忽略双重<;=和>;=要求,c#,code-contracts,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 th

我有一个利用.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;
    }
}

但是,即使
Contract.Requires
未能抛出所需的异常,静态代码分析也会将每个断言标记为正确。有趣的是,当我将值的类型更改为
int
或者如果我替换
时,它会警告我存在违规行为,我希望您可能会错过安装Microsoft code contract

您可以从Microsoft Research下载Microsoft代码合同:


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

出于兴趣,为什么不允许0作为有效值?我确实希望允许0作为有效值。契约应该确保每个值都>=0。非常有趣,我会尝试联系Francesco,检查是否在“项目属性”->“代码契约”选项卡上打开了静态分析。您是否也尝试过“值>=0”表单?:)我明白了,是我的错。我想这正是它的顺序<代码>值>=0
可能更具可读性。与结果相同,
Contract.assures(Contract.result()>=0)更具可读性。请参阅此以了解更多详细信息。Joseph,我正确安装了代码契约。正如您在我的问题中所看到的,代码契约在一般情况下是有效的,而在上面提到的特定情况下却无法起作用。
class Program
{
    static void Main(string[] args)
    {

        var barMansSquareroot = new ContractSquareRoot();

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

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