加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:28:14 所属栏目:百科 来源:网络整理
导读:我有一些工厂方法 public T CreateT () where T : class { Contract.Ensures(Contract.ResultT() != null); T result = this.unityContainer.ResolveT(); return result; } 我试图建立项目我得到警告: CodeContracts:确保未证明:Contract.Result()!= nul
我有一些工厂方法
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.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读