产量突破; - 疯狂的行为

mo.*_*mo. 6 .net c# yield break

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main (string[] args)
        {
            var test1 = Test1(1, 2);
            var test2 = Test2(3, 4);
        }

        static IEnumerable Test1(int v1, int v2)
        {
            yield break;
        }

        static IEnumerable Test2 (int v1, int v2)
        {
            return new String[] { };
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

"test1"似乎是一个IEnumerable,其中v1和v2(params)为字段,而"Test1"未被调用.

"Test2"工作"设计":)

这是怎么回事?

Jon*_*eet 15

Test1 调用,但除非你遍历结果,否则你不会遇到断点yield break.

基本上Test1转换为一个IEnumerable为你实现的状态机...但你的方法的所有主体都在那个状态机内,除非你通过调用然后(或使用循环)使用状态机你将看不到你的身体执行.GetEnumerator()MoveNext()foreach

有关更多信息,请参阅我的一般迭代器文章和我的迭代器实现文章,以及Eric Lippert的两篇博客文章:Psychic Debugging第一部分Psychic Debugging第二部分.