在yield-return方法中未触发的断点
本文关键字:断点 yield-return 方法 | 更新日期: 2023-09-27 18:11:44
我的函数是这样的
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);
我什么也没得到,我做错了什么?
这是因为所有的'yield '都被转换为惰性枚举。
IEnumerable<IPublishedContent> posts1 = GetAllowedBlogs(node);
这一行仅创建了 blog的枚举,但是不执行它。
还没有真正运行。
试试这个,看看你的断点是否有效:
IEnumerable<IPublishedContent> posts1 = GetAllowedBlogs(node).ToList();
(。ToList来自System。(当然是Linq命名空间)
仅供参考:这不是问题的重点,但您可能会发现看到yield
真正编译成什么很有趣。这个链接下的代码和解释可能有点旧了,但要点仍然适用:http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx
Lazy Evaluation.
在开始使用posts1.
您应该通过调用ToList ToArray等方法之一来实现序列,这些方法将实际执行您的代码。