可用作 IEnumerable 和 Single 对象的 C# 对象

标签 c# ienumerable

是否有更好/更好的方法来执行以下操作?

  • 可以用作普通对象并访问其属性和/或用作对象的 IEnumerable 集合的对象。见以下代码:

示例:

static void Main(string[] args)
{
    Item i = new Item() {Name="Erik"};
    i.Add(new Item() {Name="Fred"});
    i.Add(new Item() {Name="Bert"});

    // First access the object as collection and foreach it
    Console.WriteLine("=> Collection of Items");
    foreach (Item item in i)
        Console.WriteLine(item.Name);

    // Access a single property on the object that gives back the first element in the list.
    Console.WriteLine("=> Single Item");
    Console.WriteLine(i.Name);

    Console.ReadLine();
}


public class Item : IEnumerable<Item>
{
    public void Add(Item item)
    {
        _items.Add(item);
        UpdateInnerList();
    }

    #region Fields

    private List<Item> _items = new List<Item>();
    private List<Item> _innerList = new List<Item>();           
    private string _name = string.Empty;

    #endregion

    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            UpdateInnerList();
        }
    }

    #region Methods

    public IEnumerator<Item> GetEnumerator()
    {
        return _innerList.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return _innerList.GetEnumerator();
    }

    private void UpdateInnerList()
    {
        _innerList.Clear();
        _innerList.Add(this);
        _innerList.AddRange(_items);
    }

    #endregion
}

最佳答案

这看起来很像一棵树,尽管我通常使用像这样的 Tree 类更明确地对其进行建模:

public class Tree<T>
{
    public T Item { get; set; }

    public IList<T> Children { get; }
}

您的代码看起来像是树和 Composite 的组合,尽管您还不完全在那里,因为枚举器不包括“根”项。

目前的设计似乎有点不对劲。我会把它更多地拉向像上面那样的显式树的方向,或者拉向真正的复合体。

关于可用作 IEnumerable 和 Single 对象的 C# 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2264767/

相关文章:

c# - 越来越具体的十进制数的计算影响是什么

c# - 获取通用列表项的计数

c# - 有没有办法结合foreach循环

c# - 如何将依赖项传递给 Serilog Enricher?

c# - IEnumerable IEnumerator 带或不带 Current moveNext 重置

linq - 如何在 View 中使用 IGrouping 处理 IEnumerable?

c# - 将多行字符串变量从 C# 传递到 javascript

c# - yield return 奇怪的行为

c# - 转换字典<int, List<User>>

asp.net - LINQ:按列表中唯一项目的数量排序<string>