【问题标题】:Debugger does not hit breakpoint调试器未命中断点
【发布时间】:2010-11-05 01:19:38
【问题描述】:

我发现了一些很奇怪的东西(我想!)。如果我尝试在 yes() 方法中放置断点,它在执行函数时将永远不会暂停程序。如果我尝试对任何其他代码行执行相同的操作,它将按预期工作。这是一个错误,还是有什么东西在逃避我?

过滤器将返回 2 个对象,除调试器外,一切似乎都按预期工作。

private void Form1_Load(object sender, EventArgs e) {
    List<LOL> list = new List<LOL>();
    list.Add(new LOL());
    list.Add(new LOL());

    IEnumerable<LOL> filter = list.Where(
        delegate(LOL lol) {
            return lol.yes();
        }
    );

    string l = "";   <------this is hit by the debugger
}

class LOL {
    public bool yes() {
        bool ret = true; <---------this is NOT hit by the debugger
        return ret;
    }
}

【问题讨论】:

标签: c# delegates debugging list breakpoints


【解决方案1】:

Enumerable.Where 是一个惰性运算符 -- 直到您调用通过 where 返回的 IEnumerable 的东西(即在其上调用 .ToList()),您的函数才会被调用。

尝试将您的代码更改为此,看看它是否被调用:

....
IEnumerable<LOL> filter = list.Where(
    delegate(LOL lol) {
        return lol.yes();
    }
).ToList();

string l = "";

【讨论】:

    【解决方案2】:

    您必须具体化列表。添加...

    filter.ToList();
    

    ... 在声明之后,您将遇到断点。关于我见过的最好的讨论是here。它的惰性求值比我能做的要好得多。

    【讨论】:

      【解决方案3】:

      正如其他人所说,您刚刚定义了您的标准,但还没有要求执行。这称为延迟加载(各位,如果我错了,请纠正我)。

      在过滤器上运行一个 foreach 循环,看看会发生什么。

      【讨论】:

        【解决方案4】:

        乔纳森是正确的。

        尝试运行此控制台应用程序并在指示的位置设置断点以清楚地看到它。

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        
        namespace ConsoleApplication1
        {
            class Program
            {
                static void Main(string[] args)
                {
                    List<LOL> list = new List<LOL>();
                    list.Add(new LOL());
                    list.Add(new LOL());
        
                    IEnumerable<LOL> filter = list.Where(
                        delegate(LOL lol)
                        {
                            return lol.yes();
                        }
                    );
        
                    // Breakpoint #2 will not have been yet.
                    Console.Write("No Breakpoint"); // Breakpoint #1 
                    // (Breakpoint #2 will now be hit.)
                    Console.Write("Breakpoint! " + filter.Count()); 
                }
        
                class LOL
                {
                    public bool yes()
                    {
                        bool ret = true; // Breakpoint #2
                        return ret;
                    }
        
                }
        
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-10-07
          • 2011-10-11
          • 2013-11-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-23
          • 2011-10-30
          相关资源
          最近更新 更多