c# – 如何使代码合同相信变量不为null?

我有一些工厂方法
public T Create<T> () where T : class 
    {
        Contract.Ensures(Contract.Result<T>() != null);

        T result = this.unityContainer.Resolve<T>();

        return result;
    }

我试图建立项目我得到警告:

CodeContracts:确保未证明:Contract.Result()!= null

我知道IUnityContainer接口没有任何合同,所以代码合同认为可变的可能是null,没有办法证明Create()将返回不为null结果.

在这种情况下,我可以使代码合同相对于该结果变量不为空吗?

我首先尝试调用Contract.Assert

public T Create<T> () where T : class 
    {
        Contract.Ensures(Contract.Result<T>() != null);

        T result = this.unityContainer.Resolve<T>();

        Contract.Assert(result != null);

        return result;
    }

但是我需要另外一个警告:

CodeContracts:断言未经证实

我试着检查null,这使所有的警告消失了:

public T Create<T> () where T : class 
    {
        Contract.Ensures(Contract.Result<T>() != null);

        T result = this.unityContainer.Resolve<T>();

        if (result == null)
        {
            throw new InvalidOperationException();
        }

        return result;
    }

但我不知道这是手动抛出异常的好方法.可能有一些方法可以使用代码合同来解决问题吗?

谢谢.

解决方法

我想你想要 Contract.Assume
Contract.Assume(result != null);

从文档:

Instructs code analysis tools to assume that the specified condition is true,even if it cannot be statically proven to always be true.

如果您正确配置重写器,这仍将在执行时验证结果.

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么