【发布时间】:2012-07-04 20:25:15
【问题描述】:
我有一个必须为非空的IEnumerable 参数。如果有像下面这样的先决条件,那么将在此期间枚举集合。但是下次我引用它时会再次枚举,从而在 Resharper 中导致“IEnumerable 的可能多次枚举”警告。
void ProcessOrders(IEnumerable<int> orderIds)
{
Contract.Requires((orderIds != null) && orderIds.Any()); // enumerates the collection
// BAD: collection enumerated again
foreach (var i in orderIds) { /* ... */ }
}
这些变通办法让 Resharper 很高兴,但无法编译:
// enumerating before the precondition causes error "Malformed contract. Found Requires
orderIds = orderIds.ToList();
Contract.Requires((orderIds != null) && orderIds.Any());
---
// enumerating during the precondition causes the same error
Contract.Requires((orderIds != null) && (orderIds = orderIds.ToList()).Any());
还有其他有效但可能并不总是理想的解决方法,例如使用 ICollection 或 IList,或执行典型的 if-null-throw-exception。
是否有像原始示例中那样适用于代码协定和 IEnumerables 的解决方案?如果没有,那么是否有人开发了一个很好的模式来解决它?
【问题讨论】:
-
我认为有一个依赖于 IEnumerable 的合同可能只是一个坏主意 - 因为根据定义,IEnumerables 会产生副作用。
-
到目前为止,我使用 ICollection 作为一种解决方法并且从未遇到过问题,但我很好奇是否有针对 IEnumerables 的解决方案。
标签: c# .net ienumerable validation code-contracts