我正在尝试使用 Yield 设置递归逻辑。这是我的场景:我有一个 NodeviewModel 项的集合,每个 NodeviewModel 项可以有多个 NodeViewModel 项类型的子项。图的深度可以是“n”。基本上,我得到 NodeviewModel 项目并转换成不同的形式。
这是代码:
public class CompositeContentBuilder
{
private readonly IContentFactory _contentFactory;
public CompositeContentBuilder(IContentFactory contentFactory)
{
_contentFactory = contentFactory;
}
public IEnumerable<IContentViewModel> BuildFrom(IEnumerable<INodeViewModel> nodes)
{
if (nodes.Count() == 1)
yield return BuildFrom(nodes.First());
foreach (var nodeViewModel in nodes)
{
yield return BuildFrom(nodeViewModel);
foreach (var viewModel in nodeViewModel.Children)
{
yield return BuildFrom(viewModel);
}
//How do I return children.children...and so on?
}
}
private IContentViewModel BuildFrom(INodeViewModel node)
{
var content = _contentFactory.Create(node);
content.Initialise();
return content;
}
}
我将如何转换 children.children 等?能否请你帮忙?