为什么我们不能为以下代码调试带有yield return的方法? [英] Why can't we debug a method with yield return for the following code?

查看:178
本文介绍了为什么我们不能为以下代码调试带有yield return的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的代码:

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();控件达到了这一点并在调试窗口中正确显示了结果.但是,为什么控件没有停止在FilterWithYield方法中呢?

I have a break point in FilterWithYield Method but its not at all hitting the break point. I have one break at the calling point i.e var sn = FilterWithYield(); Control hits this point and shows the result correctly in debugging window. But why isn't the control stopping in the FilterWithYield method?

还有一个问题.我读到yield会将数据返回给调用方.如果是这样,则将FilterWithYield方法的返回类型更改为通过错误将其转换为int.yield关键字是否始终需要IEnumerable<T>作为返回类型?

One more question. I read that yield returns data to the caller..if that is so if changed return type of FilterWithYield method to int it through error.Does the yield key word always need IEnumerable<T> as return type?

推荐答案

您可以调试该方法.问题是,您尝试访问的代码永远不会执行.

You can debug the method. The problem is, the code that you are trying to reach is never executed.

IEnumerable方法生成的代码使您的序列在进行枚举时变得懒惰.但是,当您这样做

IEnumerable methods with yield return produce code that makes your sequence lazily, as you go through enumeration. However, when you do this

var sn = FilterWithYield();

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

you prepare to enumerate the sequence, but you do not start enumerating it.

反之,如果您添加一个foreach循环或对该结果调用ToList(),则您的断点将被命中:

If, on the other hand, you add a foreach loop or call ToList() on the result, your breakpoint would get hit:

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

var sn = FilterWithYield().ToList();

这篇关于为什么我们不能为以下代码调试带有yield return的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆