【问题标题】:Can someone explain why the nested yield return executes (C# yield return)? [duplicate]有人可以解释为什么执行嵌套的收益返回(C# 收益返回)吗? [复制]
【发布时间】:2013-05-31 02:00:03
【问题描述】:
using System.Reflection;

internal class TestReflection
{
    public static IEnumerable<object> ParseType(Type t)
    {
        foreach (MemberInfo mi in t.GetMembers())
        {
            yield return mi;
            foreach (object x in mi.GetCustomAttributes(true))
            {
                yield return x;
            }
        }
    }
}

所以我的问题是迭代器如何知道何时进入嵌套的 foreach。我曾假设第一个收益返回将始终执行,而嵌套的收益返回永远不会执行。但事实并非如此,这表明我对 yield return 语句有些不太了解。

谁能解释一下?

谢谢 詹姆斯

【问题讨论】:

标签: c#


【解决方案1】:

如果只从枚举器请求单个元素,那么您是对的,但如果请求更多元素,则内部 foreach 必须执行以产生更多元素。

【讨论】:

    猜你喜欢
    • 2012-08-27
    • 2013-12-11
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    • 2011-07-01
    相关资源
    最近更新 更多