0
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 的内容相同)用于搜索方法

4

1 回答 1

0

如果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
    }
}
于 2013-03-19T23:08:06.133 回答