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

标签 c# code-contracts

我在构造函数中指定参数不为空。这些字段是私有(private)的,没有其他代码可用于静态检查以怀疑这些字段是否设置为空。

然而,我从 Visual Studio 2013 收到警告,它们可能为空。

CodeContracts: Possibly accessing a field on a null reference '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
    }

}

编辑:

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

最佳答案

根据您的项目设置,我不相信静态检查器总能计算出origindestination 上的不变量。

有几种方法可以用来解决这个警告:

ContractInvariantMethod

添加一个带有 ContractInvariantMethodAttribute 属性的显式私有(private)方法,并调用 Contract.Invariant,例如:

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

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

只读 + 为只读推断不变量

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

Infer invariants for readonly field screenshot

我个人倾向于采用 ContractInvariantMethod 方法,但如果它们仅在实例化时初始化,我也会将我的字段标记为 readonly,但这两种方法都应该有效。

关于c# - Contract.Requires 不阻止空引用警告(紫色波浪形),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28974478/

相关文章:

c# - 从 NHibernate 配置文件生成数据库

c# - 如何更改图表标签的前景色?

c# - 代码契约(Contract)和规范之间的区别#

c# - 代码契约——是否应该检查私有(private)方法的前置条件和后置条件?

haskell - 将契约设计与类型系统进行比较

vb.net - 在 VB.NET 项目中强制执行代码契约的编译时检测

c# - 创建C#验证类的好方法

c# - 如何在 C# 中使用反射获取 Json 属性名称

c# - 制作多语言网站的最佳方式

c# - 代码契约构建引用装配 Action