C# 为什么静态分析忽略双重<;=和>;=要求
我有一个利用.NET代码契约的非常简单的类: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
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));