foreach 与 ForEach 使用 yield

foreach vs ForEach using yield

是否可以在 ForEach 方法中使用 yield 内联?

private static IEnumerable<string> DoStuff(string Input)
{
    List<string> sResult = GetData(Input);
    sResult.ForEach(x => DoStuff(x));

    //does not work
    sResult.ForEach(item => yield return item;); 

    //does work
    foreach(string item in sResult) yield return item;
}

如果不是,是否有它不起作用的原因?

不,List<T>.ForEach 不能用于此。

List<T>.ForEach 接受了 Action<T> 委托。

Action<T> "Encapsulates a method that has a single parameter and does not return a value."

所以你创建的 lambda 不能 return 任何东西,如果它是 "fit" 在 Action<T>.

因为如您所见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>