foreach vs ForEach使用yield

时间:2016-03-09 15:58:36

标签: c# yield

是否可以在true方法中使用find内联?

yield

如果没有,是否有理由不起作用?

2 个答案:

答案 0 :(得分:9)

不,List<T>.ForEach无法用于此目的。

List<T>.ForEach需要Action<T>代表。

Action<T>&#34;封装具有单个参数且不返回值的方法。&#34;

所以你创建的lambda如果符合&#34;适合&#34;那么它将无法返回任何内容。在Action<T>

答案 1 :(得分:7)

因为你可以看到here lambda函数被编译成一个单独的方法:

此:

x => DoStuff(x)

转换为

internal void <DoStuff>b__1_0(string x)
{
    C.DoStuff(x);
}

此单独方法不是IEnumerable<>,因此它显然不支持yield关键字。

例如:

item => yield return item;

将转换为:

internal void <DoStuff>b__1_0(string item)
{
    yield return item;
}

具有yield但不是IEnumerable<string>

相关问题