【问题标题】:How to use foreach on a list of lists that on another class如何在另一个类上的列表列表上使用 foreach
【发布时间】:2013-03-19 22:19:53
【问题描述】:
public class ItemCollection
{
    List<AbstractItem> LibCollection;

    public ItemCollection()
    {
        LibCollection = new List<AbstractItem>(); 
    }

    public List<AbstractItem> ListForSearch()
    {
        return LibCollection;
    }

在另一堂课上我写了这个:

public class Logic
{
    ItemCollection ITC;

    List<AbstractItem> List;

    public Logic()
    {
        ITC = new ItemCollection();   

        List = ITC.ListForSearch();    
    }

    public List<AbstractItem> search(string TheBookYouLookingFor)
    {
        foreach (var item in List)
        {
          //some code..
        }

并且 foreach 中的列表不包含任何内容 我需要为搜索方法处理这个列表(这个列表应该与 libcollection 的内容相同)

【问题讨论】:

  • 据我所知,List(btw 的名字很可怕)ItemCollection.LibCollection 相同的引用。
  • 定义“不包含任何内容”。是null吗?还是它被实例化并且只是空的?在后一种情况下,我看不到您在列表中实际添加任何内容的位置...
  • Item Collection 变得没用了,你用它来封装列表,然后你暴露列表!您要么需要将搜索功能移动到 ItemCollection,要么摆脱项目集合。

标签: c# list foreach


【解决方案1】:

如果ItemCollection 除了拥有List&lt;AbstractItem&gt; 之外没有其他用途,那么可能应该完全删除该类并改用List&lt;AbstractItem&gt;

如果ItemCollection有其他用途,其他人不应该访问底层List&lt;AbstractItem&gt;,它可以实现IEnumerable&lt;AbstractItem&gt;

class ItemCollection : IEnumerable<AbstractItem>
{
    List<AbstractItem> LibCollection;

    public ItemCollection() {
        this.LibCollection = new List<AbstractItem>();
    }

    IEnumerator<AbstractItem> IEnumerable<AbstractItem>.GetEnumerator() {
        return this.LibCollection.GetEnumerator();
    }

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

class Logic
{
    ItemCollection ITC;

    public Logic() {
        ITC = new ItemCollection();
    }

    public List<AbstractItem> Search(string TheBookYouLookingFor) {
        foreach (var item in this.ITC) {
            // Do something useful
        }
        return null; // Do something useful, of course
    }
}

否则,您可能希望直接公开LibCollection 并让其他代码对其进行枚举:

class ItemCollection
{
    public List<AbstractItem> LibCollection { get; private set; }

    public ItemCollection() {
        this.LibCollection = new List<AbstractItem>();
    }
}

class Logic
{
    ItemCollection ITC;

    public Logic() {
        ITC = new ItemCollection();
    }

    public List<AbstractItem> Search(string TheBookYouLookingFor) {
        foreach (var item in this.ITC.LibCollection) {
            // Do something useful
        }
        return null; // Do something useful
    }
}

【讨论】:

  • 我尝试了两种方法,但都没有解决这个问题,我需要在另一个类(逻辑)的这个项目列表(LibCollection)上使用“foreach”。我认为这比实际上更容易。非常感谢
猜你喜欢
  • 2021-01-15
  • 2018-05-01
  • 2019-09-21
  • 2022-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多