为什么要使用yield关键字,当我可以只使用一个普通的IEnumerable? [英] Why use the yield keyword, when I could just use an ordinary IEnumerable?

查看:154
本文介绍了为什么要使用yield关键字,当我可以只使用一个普通的IEnumerable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于此代码:

IEnumerable<object> FilteredList()
{
    foreach( object item in FullList )
    {
        if( IsItemInPartialList( item ) )
            yield return item;
    }
}



为什么我不只是代码这种方式?:

Why should I not just code it this way?:

IEnumerable<object> FilteredList()
{
    var list = new List<object>(); 
    foreach( object item in FullList )
    {
        if( IsItemInPartialList( item ) )
            list.Add(item);
    }
    return list;
}



我有点明白什么收益关键字一样。它告诉编译器来构建某种东西(迭代器)。但是,为什么使用它?除了它是略少的代码,什么是它为我做什么?

I sort of understand what the yield keyword does. It tells the compiler to build a certain kind of thing (an iterator). But why use it? Apart from it being slightly less code, what's it do for me?

推荐答案

使用收益将集合的懒。

比方说,你只需要前五个项目。你的方式,我必须通过的整个列表循环的率先拿到五个项目。随着收益,我只通过第一五项循环。

Let's say you just need the first five items. Your way, I have to loop through the entire list to get the first five items. With yield, I only loop through the first five items.

这篇关于为什么要使用yield关键字,当我可以只使用一个普通的IEnumerable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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