如何让代码合约相信变量不为空?
我有一些工厂方法
public T Create<T> () where T : class
{
Contract.Ensures(Contract.Result<T>() != null);
T result = this.unityContainer.Resolve<T>();
return result;
}
我尝试构建项目时收到警告:
CodeContracts: Ensures unproven: Contract.Result() != null
我了解 IUnityContainer 接口没有任何合同,因此代码合同认为 varible 可能为 null,并且没有办法证明 Create() 会返回非 null 结果。
在这种情况下,我如何才能使代码契约相信 result 变量不为空?
我首先尝试调用 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: assert unproven
我尝试检查 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;
}
但我不确定这是一个好的解决方案手动抛出异常。可能有某种方法可以仅使用代码契约来解决问题吗?
谢谢。
I have some factory method
public T Create<T> () where T : class
{
Contract.Ensures(Contract.Result<T>() != null);
T result = this.unityContainer.Resolve<T>();
return result;
}
The I try to build the project i get the warning:
CodeContracts: ensures unproven: Contract.Result() != null
I understand that IUnityContainer interface does not have any contracts so Code Contracts think that varible may be null and there is no way to prove that Create() will return not null result.
How in this case I can make Code Contracts belive that result variable is not null?
I first tried to call 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;
}
But it takes me another warning:
CodeContracts: assert unproven
I tried make check for null and this makes all warnings gone:
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;
}
But i'm not sure this is good solution to throw exception manually. May be there is some way to solve problem using Code Contracts only?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您想要
Contract.Assume
:来自文档:
如果您正确配置了重写器,这仍然会在执行时验证结果。
I think you want
Contract.Assume
:From the docs:
This will still validate the result at execution time if you have the rewriter appropriately configured.
就像
if((result ?? 0) == 0){}
为了使这一点更清晰(可读),您可以定义一个扩展方法。
编辑
@allentracks 答案对于您的问题来说更准确
Like
if((result ?? 0) == 0){}
To make this more clear (readable) you can define an extension method.
Edit
@allentracks answer is more precise for your question