c# – CodeContracts:可能在空引用上调用方法

我和 CodeContracts static analysis tool有争执.

我的代码:

Screenshot http://i40.tinypic.com/r91zq9.png

(ASCII version)

该工具告诉我instance.bar可能是一个空引用.我相信相反.

谁是对的?我怎么能证明它错了?

解决方法

更新:似乎问题是 invariants are not supported for static fields.

第二次更新:下面概述的方法是currently the recommended solution.

可能的解决方法是创建一个属性,例如确保要保留的不变量. (当然,您需要假设它们才能确保被证明.)完成此操作后,您可以使用该属性,并且应该正确地证明所有不变量.

以下是使用此方法的示例:

class Foo
{
    private static readonly Foo instance = new Foo();
    private readonly string bar;

    public static Foo Instance
    // workaround for not being able to put invariants on static fields
    {
        get
        {
            Contract.Ensures(Contract.Result<Foo>() != null);
            Contract.Ensures(Contract.Result<Foo>().bar != null);

            Contract.Assume(instance.bar != null);
            return instance;
        }
    }

    public Foo()
    {
        Contract.Ensures(bar != null);
        bar = "Hello world!";
    }

    public static int BarLength()
    {
        Contract.Assert(Instance != null);
        Contract.Assert(Instance.bar != null);
        // both of these are proven ok

        return Instance.bar.Length;
    }
}

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...