为什么不能迭代方法采取或者'裁判'或'出'参数? [英] Why can't iterator methods take either 'ref' or 'out' parameters?

查看:688
本文介绍了为什么不能迭代方法采取或者'裁判'或'出'参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这今天早些时候我尝试:

I tried this earlier today:

public interface IFoo
{
    IEnumerable<int> GetItems_A( ref int somethingElse );
    IEnumerable<int> GetItems_B( ref int somethingElse );
}


public class Bar : IFoo
{
    public IEnumerable<int> GetItems_A( ref int somethingElse )
    {
        // Ok...
    }

    public IEnumerable<int> GetItems_B( ref int somethingElse )
    {
        yield return 7; // CS1623: Iterators cannot have ref or out parameters            

    }
}

什么是这背后的原因是什么?

What's the rationale behind this?

推荐答案

C#迭代器内部状态机。每次收益回报率的东西,你离开的地方,应与局部变量的状态一起保存时间,这样你可以回去,并从那里继续。

C# iterators are state machines internally. Every time you yield return something, the place where you left off should be saved along with the state of local variables so that you could get back and continue from there.

要保存该状态,C#编译器创建一个类来保存局部变量和应继续从地方。这是不可能有一个 REF 退出值作为一个类的字段。因此,如果你被允许申报一个参数为 REF 退出,就没有办法保持完整。在我们已经离开的时间函数的快照

To hold this state, C# compiler creates a class to hold local variables and the place it should continue from. It's not possible to have a ref or out value as a field in a class. Consequently, if you were allowed to declare a parameter as ref or out, there would be no way to keep the complete snapshot of the function at the time we had left off.

编辑:从技术上讲,不是所有的返回方式的IEnumerable< ; T> 被认为是迭代器。只是那些使用收益来产生一个直接序列被认为是迭代器。因此,虽然分裂迭代器两种方法是一个很好的和共同的解决办法,它不与我刚才说的矛盾。外法(即不使用收益直接)是的不可以视为一个迭代器。

Technically, not all methods that return IEnumerable<T> are considered iterators. Just those that use yield to produce a sequence directly are considered iterators. Therefore, while the splitting the iterator into two methods is a nice and common workaround, it doesn't contradict with what I just said. The outer method (that doesn't use yield directly) is not considered an iterator.

这篇关于为什么不能迭代方法采取或者'裁判'或'出'参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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