yield关键字是c#中一直困扰我的关键字之一,我从来都不确定自己是否正确地使用了它。

在以下两段代码中,哪一段是首选的,为什么?

版本1:使用收益率

public static IEnumerable<Product> GetAllProducts()
{
    using (AdventureWorksEntities db = new AdventureWorksEntities())
    {
        var products = from product in db.Product
                       select product;

        foreach (Product product in products)
        {
            yield return product;
        }
    }
}

版本2:返回列表

public static IEnumerable<Product> GetAllProducts()
{
    using (AdventureWorksEntities db = new AdventureWorksEntities())
    {
        var products = from product in db.Product
                       select product;

        return products.ToList<Product>();
    }
}

当前回答

这有点离题了,但由于这个问题被标记为最佳实践,我将继续发表我的意见。对于这种类型的东西,我非常喜欢把它变成一个属性:

public static IEnumerable<Product> AllProducts
{
    get {
        using (AdventureWorksEntities db = new AdventureWorksEntities()) {
            var products = from product in db.Product
                           select product;

            return products;
        }
    }
}

当然,它更像一个样板,但使用它的代码将看起来更干净:

prices = Whatever.AllProducts.Select (product => product.price);

vs

prices = Whatever.GetAllProducts().Select (product => product.price);

注意:我不会对任何可能需要一段时间才能完成工作的方法这样做。

其他回答

以下是Chris Sells在《c#程序设计语言》中讲述的语句;

I sometimes forget that yield return is not the same as return , in that the code after a yield return can be executed. For example, the code after the first return here can never be executed: int F() { return 1; return 2; // Can never be executed } In contrast, the code after the first yield return here can be executed: IEnumerable<int> F() { yield return 1; yield return 2; // Can be executed } This often bites me in an if statement: IEnumerable<int> F() { if(...) { yield return 1; // I mean this to be the only thing returned } yield return 2; // Oops! } In these cases, remembering that yield return is not “final” like return is helpful.

我知道这是一个老问题,但我想提供一个例子,说明如何创造性地使用yield关键字。我真的从这个技巧中受益良多。希望这将有助于任何人谁偶然遇到这个问题。

注意:不要认为yield关键字仅仅是构建集合的另一种方式。收益率的很大一部分力量来自于这样一个事实,即在执行过程中暂停 方法或属性,直到调用代码遍历下一个值。以下是我的例子:

使用yield关键字(与Rob Eisenburg的Caliburn一起使用)。微协程实现)允许我像这样表达对web服务的异步调用:

public IEnumerable<IResult> HandleButtonClick() {
    yield return Show.Busy();

    var loginCall = new LoginResult(wsClient, Username, Password);
    yield return loginCall;
    this.IsLoggedIn = loginCall.Success;

    yield return Show.NotBusy();
}

这将做的是打开我的BusyIndicator,在我的web服务上调用Login方法,将我的IsLoggedIn标志设置为返回值,然后关闭BusyIndicator。

Here's how this works: IResult has an Execute method and a Completed event. Caliburn.Micro grabs the IEnumerator from the call to HandleButtonClick() and passes it into a Coroutine.BeginExecute method. The BeginExecute method starts iterating through the IResults. When the first IResult is returned, execution is paused inside HandleButtonClick(), and BeginExecute() attaches an event handler to the Completed event and calls Execute(). IResult.Execute() can perform either a synchronous or an asynchronous task and fires the Completed event when it's done.

LoginResult看起来像这样:

public LoginResult : IResult {
    // Constructor to set private members...

    public void Execute(ActionExecutionContext context) {
        wsClient.LoginCompleted += (sender, e) => {
            this.Success = e.Result;
            Completed(this, new ResultCompletionEventArgs());
        };
        wsClient.Login(username, password);
    }

    public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
    public bool Success { get; private set; }
}

它可能有助于设置类似这样的东西,并逐步执行以观察发生了什么。

希望这能帮助到一些人!我真的很喜欢探索不同的收益使用方式。

填充一个临时列表就像下载整个视频,而使用yield就像流媒体视频。

直接返回列表。好处:

这样就更清楚了 该列表是可重用的。(迭代器不是)不是真的,谢谢Jon

You should use the iterator (yield) from when you think you probably won't have to iterate all the way to the end of the list, or when it has no end. For example, the client calling is going to be searching for the first product that satisfies some predicate, you might consider using the iterator, although that's a contrived example, and there are probably better ways to accomplish it. Basically, if you know in advance that the whole list will need to be calculated, just do it up front. If you think that it won't, then consider using the iterator version.

当我计算列表中的下一项(甚至是下一组项)时,我倾向于使用yield-return。

使用版本2,在返回之前必须有完整的列表。 通过使用yield-return,您实际上只需要在返回前获得下一项。

除此之外,这有助于在更大的时间框架内分散复杂计算的计算成本。例如,如果列表连接到GUI,而用户从未访问到最后一页,则永远不会计算列表中的最终项。

yield-return更可取的另一种情况是IEnumerable表示无限集。考虑素数列表,或者无限随机数列表。您永远不能一次返回完整的IEnumerable,因此使用yield-return以增量方式返回列表。

在您的特定示例中,您拥有完整的产品列表,因此我将使用版本2。