CodeContract 认为分配的只读字段可以为 null
我有这个代码:
public class CodeContractSample
{
private readonly List<object> _items = new List<object>();
public IEnumerable<object> Query()
{
Contract.Ensures(Contract.Result<IEnumerable<object>>() != null);
//if (_items == null) throw new Exception();
return _items;
}
}
CodeContracts 给出了这个警告:
CodeContracts:确保未经验证:Contract.Result>() != null
如果我取消注释中间行,它就会停止抱怨。但为什么它一开始就会抱怨呢? _items 永远不应该为空..?
I've got this code:
public class CodeContractSample
{
private readonly List<object> _items = new List<object>();
public IEnumerable<object> Query()
{
Contract.Ensures(Contract.Result<IEnumerable<object>>() != null);
//if (_items == null) throw new Exception();
return _items;
}
}
CodeContracts gives this warning:
CodeContracts: ensures unproven: Contract.Result>() != null
If I uncomment the middle row it stops complaining. But why does it complain to start with? _items should never be null..?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
合同不是 100% 的,它的理解仍然存在差距。
你是对的:结果没有理由未经证实。请参阅 http://social. msdn.microsoft.com/Forums/en-US/codecontracts/thread/f82aa25c-e858-4809-bc21-0a08de260bf1 有关此特定问题的详细信息。
现在,您可以使用以下方法解决此问题:
您还可以使用契约不变量来实现此目的:
Contracts are not 100% and there are still gaps in what it understands.
You are right: there is no reason for the result being unproven. See http://social.msdn.microsoft.com/Forums/en-US/codecontracts/thread/f82aa25c-e858-4809-bc21-0a08de260bf1 for more information on this specific issue.
For now, you can solve this using:
You can also achieve this using contract invariants:
为什么你认为 items 永远不会为 null?您可以在该类中使用另一个方法将其设置为 null ...
Why do you think items will never be null? You could have another method in that class that sets it to null ...
其实我可以想象:
你觉得怎么样?
Actually i can imagine this:
What do You think ?
Contract.Ensures 行承诺该方法永远不会返回 null。但在您取消注释该行之前,代码中没有任何内容可以阻止这种情况。
The Contract.Ensures line is making a promise that the method will never return null. But there is nothing in the code that prevents this until you uncomment the line.