foreach vs ForEach使用yield

fub*_*ubo 5 c# yield

是否可以yieldForEach方法中使用内联?

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;
}
Run Code Online (Sandbox Code Playgroud)

如果没有,有什么理由不起作用?

小智 9

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

List<T>.ForEach接一个Action<T>代表.

Action<T> "封装具有单个参数且不返回值的方法."

所以你创建的lambda如果要"适合",就不能返回任何东西Action<T>.


xan*_*tos 7

因为正如你在这里看到的那样,lambda函数被编译为一个单独的方法:

这个:

x => DoStuff(x)
Run Code Online (Sandbox Code Playgroud)

转换为

internal void <DoStuff>b__1_0(string x)
{
    C.DoStuff(x);
}
Run Code Online (Sandbox Code Playgroud)

这个单独的方法不是IEnumerable<>这样,它显然不能支持yield关键字.

所以例如:

item => yield return item;
Run Code Online (Sandbox Code Playgroud)

将被转换为:

internal void <DoStuff>b__1_0(string item)
{
    yield return item;
}
Run Code Online (Sandbox Code Playgroud)

yield但不是IEnumerable<string>.