对迭代器项的后置条件,避免多次迭代 [英] Postconditions on iterator items that avoid multiple iterations

查看:84
本文介绍了对迭代器项的后置条件,避免多次迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前仅支持后置条件,如果使用 Contract.ForAll
方法或 Enumerable.All 扩展方法,例如:

Currently postconditions are only supported if a Contract.ForAll method or Enumerable.All extension methods are used, e.g.:

IEnumerable<int> GetNumbers()
{
    Contract.Ensures(Contract.Result<IEnumerable<int>>().All(item => item > 0));

    yield return 1;
    yield return 2;
    yield return 3;
}

通过调用方法,迭代执行两次。后置条件的第一次和呼叫者的第二次。但是,该方法无法保证第二次调用会产生相同的结果。

By calling the method the iteration is performed twice. The first time for the postcondition and the second time for the caller. However, the method is not able to guarantee that the second invocation would produce the same results.

有没有办法拦截枚举(可能类似于async确保)来验证这样的结果case?

Is there a way to intercept the enumeration (may be similar to async ensures) to verify such a case?

推荐答案

这是一个常见的问题。遗憾的是,一般情况下,没有办法避免枚举两次。

This is a common question. Unfortunately, in general, there isn't a way to avoid enumerating twice.

对于您的特殊情况,可以考虑一些仅适用于每个元素的专门合同。一般来说,这些方法的签名只是返回一个可枚举的,因此,更复杂形式的契约可以写成
,例如:

For your special case, one could consider some specialized contract that only applies to each element independently. In general though, the signature of these methods is just that it returns an enumerable and so, contracts of more complicated form can be written, such as:

Contract.Ensures( IsSorted(Contract.Result< IEnumerable< int>>()));

Contract.Ensures( IsSorted(Contract.Result<IEnumerable<int>>()) );


这篇关于对迭代器项的后置条件,避免多次迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆