2013-03-19 70 views
0
public class ItemCollection 
{ 
    List<AbstractItem> LibCollection; 

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

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

,并在另一个类中,我写这:如何使用的foreach列表的列表上的其他类

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)的搜索方法

+0

从我看到的,'List'(可怕的名字btw)** **与ItemCollection.LibCollection相同的引用。 – SWeko 2013-03-19 22:25:28

+0

定义“不包含任何内容”。它是'空'吗?还是它实例化,只是空的?在后一种情况下,我没有看到你实际上在列表中添加了什么... – David 2013-03-19 22:26:15

+0

项目集合变得没用,你用它来封装列表,然后你公开列表!您可能需要将搜索功能移至ItemCollection,或者删除项目集合。 – 2013-03-19 22:29:59

回答

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

我尝试了两种方式,它并没有解决这个问题,我需要在另一个类(逻辑)的这个项目列表(LibCollection )上使用'foreach'。我认为这比实际更容易。 非常感谢 – user2188548 2013-03-28 22:04:22

相关问题