Contract.Requires不会阻止空引用警告(紫色波浪形)

时间:2015-03-10 21:32:19

标签: c# code-contracts

我在构造函数中指定params不为null。这些字段是私有的,并且没有其他代码可用于静态检查,以确定这些字段是否设置为null。

尽管如此,我收到来自Visual Studio 2013的警告,他们可能会为空。

  

CodeContracts:可能访问空引用上的字段   ' this.origin'

他们怎么可能是空的?静态检查器可能无法解决这个问题吗?或者我做得不对?

using System.Diagnostics.Contracts;

public class Link
{

    private Shape origin;
    private Shape destination;

    public Link(Shape origin, Shape destination)
    {
        Contract.Requires(origin != null);
        Contract.Requires(destination != null);
        this.origin = origin;
        this.destination = destination;
    }

    public string OriginID()
    {
        return origin.ID; // getting purple squiggly here
    }

    public string DestinationID()
    {
        return destination.ID; // getting purple squiggly here
    }

}

编辑:

他们现在走了。我的问题仍然存在,因为我不知道我做了什么让它们消失。我没有更改此类中的任何内容,也没有更改项目设置。它只是,当我收到警告时,我的一个测试没有通过,现在,所有测试都通过了。这是当时和现在之间的唯一区别。进行测试的更改是在另一个类中,而不是这个。

1 个答案:

答案 0 :(得分:0)

根据您的项目设置,我认为静态检查程序始终无法计算origindestination上的不变量。

有几种方法可以解决此警告:

<强> ContractInvariantMethod

添加一个由ContractInvariantMethodAttribute归属的显式私有方法,并调用Contract.Invariant,例如:

[ContractInvariantMethod]
private void ObjectInvariant()
{
    Contract.Invariant(origin != null);
    Contract.Invariant(destination != null);
}

这将告知静态检查器永远不会违反这些不变量,即origindestination永远不会为空。

readonly +推断readonly的不变量

将这两个字段标记为只读并在代码合同设置中,确保为静态检查器选中Infer invariants for readonly选项:

Infer invariants for readonly field screenshot

我个人倾向于采用ContractInvariantMethod方法,但如果仅在实例化时初始化我的字段readonly,那么这两种方法都应该有效。