2013-03-19 40 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

相關問題