为什么我们不能为以下代码调试 yield return 的方法?

Why can't we debug a method with yield return for the following code?

以下是我的代码:

class Program {
    static List<int> MyList;
    static void Main(string[] args) {
        MyList = new List<int>() { 1,24,56,7};
        var sn = FilterWithYield();
    }
    static IEnumerable<int> FilterWithYield() {
        foreach (int i in MyList) {
            if (i > 3)
                yield return i;
        }
    }
}

我在 FilterWithYield 方法中有一个断点,但它根本没有达到断点。我在调用点有一个中断,即 var sn = FilterWithYield(); 控件命中此点并在调试 window 中正确显示结果。但是为什么控件不在 FilterWithYield 方法中停止呢?

还有一个问题。我读到调用者的 yield returns 数据..如果是这样,如果将 return 类型的 FilterWithYield 方法更改为通过 error.Does int yield 关键字总是需要 IEnumerable<T> 作为 return 类型?

您可以调试该方法。问题是,您尝试访问的代码从未执行过。

IEnumerable 方法与 yield return 生成的代码使您的序列在您进行枚举时变得惰性。然而,当你这样做时

var sn = FilterWithYield();

您准备枚举序列,但没有开始枚举。

另一方面,如果您添加一个 foreach 循环或对结果调用 ToList(),您的断点将被命中:

foreach (var n in FilterWithYield()) {
    Console.WriteLine(n);
}

var sn = FilterWithYield().ToList();