代码契约迭代器中的错误?
以下代码在前提条件下失败。 这是代码合约中的错误吗?
static class Program
{
static void Main()
{
foreach (var s in Test(3))
{
Console.WriteLine(s);
}
}
static IEnumerable<int>Test (int i)
{
Contract.Requires(i > 0);
for (int j = 0; j < i; j++)
yield return j;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是博客文章 与这个主题相关,涉及单元测试、迭代器、延迟执行和您。
延迟执行就是这里的问题。
Here's a blog post related to this very subject concerning unit testing, iterators, delayed execution, and you.
Delayed execution is the issue here.
此代码将与 .NET 4.0 的最终版本(刚刚尝试过)一起使用,其中支持交互器中的代码契约,但正如我最近发现的那样,它并不总是能正常工作(了解更多此处)。
This code will work with final version of .NET 4.0 (just tried it) where Code Contracts in interators are supported, but as I found out recently it does not always work properly (read more here).
这可能是过去 CodeContract 重写器中的一个问题。 但当前版本似乎在您的示例中表现良好。 这里不存在迭代器/延迟评估等问题。参数 i 由值捕获,并且在迭代期间不会改变。 合约应该仅在调用 Test 开始时检查这一点,而不是在每次迭代期间检查。
This may have been a problem in the CodeContract rewriter in the past. But the current version seems to do fine on your example. There's no issue here with iterators/delayed evaluation etc. The parameter i is captured by value and won't change during the iteration. Contracts should check this only at the beginning of the call to Test, not during each iteration.
我的猜测是这与迭代器的延迟性质有关。 请记住,合同处理将发生在最终发出的 IL 上,而不是 C# 代码上。 这意味着您必须考虑迭代器和 lambda 表达式等功能的生成代码。
如果你反编译该代码,你会发现“i”实际上并不是一个参数。 它将是类中用于实现迭代器的变量。 所以代码实际上看起来更像下面这样,
我对合约 API 不太熟悉,但我的猜测是生成的代码更难验证。
My guess is this has to do with the delayed nature of iterators. Remember, contract processing will occur on the final emitted IL, not the C# code. This means you have to consider the generated code for features like iterators and lambda expressions.
If you decompile that code you'll find that "i" is not actually a parameter. It will be a variable in the class which is used to implement the iterator. So the code actually looks more like the following
I'm not terribly familiar with the contract API but my guess is the generated code is much harder to verify.
请记住,迭代器在枚举之前不会运行,并在后端编译成一些特殊的酱汁。 如果你想验证参数,你应该遵循的一般模式(这可能适用于合约)是有一个包装函数:
这样 Test() 将在调用时检查参数,然后返回 _Test(),它实际上只是返回一个新类。
Remember that iterators aren't run until they are enumerated, and are compiled into some special sauce in the back end. The general pattern you should follow if you want to validate parameters, and this probably holds true for contracts, is to have a wrapper function:
That way Test() will do the checking of the parameters when it is called then return _Test(), which actually just returns a new class.