相关疑难解决方法(0)

树中嵌套产量的性能

我有一个树状的结构.此结构中的每个元素都应该能够返回它所属的所有元素的Enumerable.我们称之为这种方法IEnumerable<Foo> GetAll().所以,如果我们有

      A <-- topmost root
    /   \
   B     C
  / \   / \
  D  E  F  G
Run Code Online (Sandbox Code Playgroud)

GetAll对元素C返回的调用{C, F, G}(元素的固定顺序很好,但不需要).我想每个人都已经知道了.

目前的实现GetAll看起来像这样:

public IEnumerable<Foo> GetAll ()
{
    yield return this;

    foreach (Foo foo in MyChildren) {
        foreach (Foo f in foo.GetAll ()) {
            yield return f;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在早期的实现中,我返回了一个List并添加了child-foos List.AddRange().

我的问题是,是否正确实施了使用产量的版本,或者是否应该改进(特别是在性能方面).或者这只是坏事我应该坚持Lists(或ReadOnlyCollections)而不是?

c# performance ienumerable yield

7
推荐指数
2
解决办法
5348
查看次数

标签 统计

c# ×1

ienumerable ×1

performance ×1

yield ×1