簡體   English   中英

如何在另一個類的列表列表上使用foreach

[英]How to use foreach on a list of lists that on another class

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相同),以用於搜索方法

如果ItemCollection除了擁有List<AbstractItem>之外沒有其他目的,則應該完全刪除該類,而只需使用List<AbstractItem>

如果ItemCollection有其他用途,而其他人不應該訪問基礎List<AbstractItem> ,則可以實現IEnumerable<AbstractItem>

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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM