簡體   English   中英

在具有yield-return的方法中未觸發斷點

[英]Breakpoints not triggered in a method with yield-return

我的功能是這樣的

 IEnumerable<IPublishedContent> GetAllowedBlogs(IEnumerable<IPublishedContent> blogLandingNodes)
{
    foreach (var node in blogLandingNodes)
    {
        if ("Condition")
        {
            var blogsToDisplay = GetPostsForBlog(node);

            foreach (var blog in blogsToDisplay)
            {
                yield return blog;
            }
        }
        else
        {
            var blogsToDisplay = GetPostsForBlog(node, catId);

            foreach (var blog in blogsToDisplay)
            {
                yield return blog;
            }
        }
    }
}

當我放置一個斷點並檢查時,我可以看到結果節點屈服,但是當我在這里檢查時

  IEnumerable<IPublishedContent> posts1 = GetAllowedBlogs(node);

我什么也沒得到,我在做什么錯?

這是因為所有“產量”都轉換為惰性枚舉。

IEnumerable<IPublishedContent> posts1 = GetAllowedBlogs(node);

此行僅創建Blog的枚舉, 而不執行它
還沒有真正運行過。

試試這個,看看您的斷點是否有效:

 IEnumerable<IPublishedContent> posts1 = GetAllowedBlogs(node).ToList();

(.ToList當然來自System.Linq命名空間)

僅供參考:這不是問題的重點,但是您可能會發現有趣的是,將yield真正匯編成什么。 該鏈接下的代碼和解釋可能有些陳舊,但主要要點仍然適用: http : //csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx

惰性評估。

在開始使用posts1之前,您不會開始運行代碼。

您應該通過調用將實際執行代碼的方法之一(例如ToList ToArray等)來實現序列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM