Class的Foreach函数

时间:2019-06-29 20:36:09

标签: c# class foreach

我创建了以下课程:

public class LocationTreeAlsTree
{
    public ComponentRef PartsOfTree { get; set; }
    public class ComponentRef
    {
        public string ID { get; set; }
        public List<ComponentRef> Children { get; set; }
    }

    static List<ComponentRef> LoadUnits(IEnumerable<XElement> 
    _componentenRef)
    {
         return _componentenRef.Select(x => new ComponentRef()
         {
              ID = x.Attribute("ref").Value,
              Children = LoadUnits(x.Elements("componentRef"))
         }).ToList();
    }

    public LocationTreeAlsTree(string _filename)
    {
         // Dateiname des LocationTree-Files
         string locationtreeFile = _filename;

         // Neuer Streamreader um Encoding UTF16 Fehler zu umgehen
         StreamReader reader = new StreamReader(locationtreeFile, Encoding.UTF8);
         XDocument doc = XDocument.Load(reader);

         // Generiere eine Tree-Struktur vom Location Tree
         List<ComponentRef> units = LoadUnits(doc.Descendants("componentRef"));
         //ComponentRef Tree = new ComponentRef();
         PartsOfTree = units.First();
         units = null;
    }
}

我尝试为此类增加foreach函数。我不知道如何对此类实现IEnumerable。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

假设您要遍历可以从IEnumerable继承的SomeClass列表,

public class LocationTreeAlsTree : IEnumerable<SomeClass>
{    
     public List<SomeClass> Something; // that is filled somewhere in class

     public IEnumerator<SomeClass> GetEnumerator()
     {
          return Something.GetEnumerator();
     }

     IEnumerator IEnumerable.GetEnumerator()
     {
          return GetEnumerator();
     }
}

现在,您可以像这样使用它:

LocationTreeAlsTree tree = new LocationTreeAlsTree();
foreach(var t in tree)
{
    // do something
}