c# - 为什么要使用 yield 关键字,而我只能使用普通的 IEnumerable?

标签 c# yield

给定这段代码:

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

为什么我不应该这样编码?:

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

我有点理解 yield 关键字的作用。它告诉编译器构建某种东西(迭代器)。但是为什么要用呢?除了稍微减少代码之外,它对我有什么用?

最佳答案

使用 yield 使集合变得惰性。

假设您只需要前五项。按照您的方式,我必须遍历整个列表 才能获得前五项。使用 yield,我只循环遍历前五个项目。

关于c# - 为什么要使用 yield 关键字,而我只能使用普通的 IEnumerable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14057788/

相关文章:

c# - 管理许多重复的、CPU 密集型任务,并行运行?

c# - 在标签中显示多行文本框文本之间的空格

flutter - 在mapEventToState 中使用yield 和Either 时测试我的 block 失败

python - 使用装饰器恢复生成器

python - 如何在 python 中生成 'flatten' 生成器?

python - mod_wsgi 产生输出缓冲区而不是返回

c# - 尝试从控制台应用程序访问Azure存储并收到异常 "Configuration system failed to initialize"

c# - 什么时候使用反射?模式/反模式

c# - N 替代和协方差支持?

javascript - 为什么 Yield 不能与请求模块一起使用?