2016-07-30 26 views
0

所以我有這個產品清單。C#如何創建從另一個類的列表的引用?

現在,我想要做的是在另一個類的foreach循環這個列表。

如何在我想要循環的類中對AllProducts進行引用?

public List<Product> AllProducts; 
AllProducts = new List<Product>(); 


foreach (product p in AllProducts) 
{ 
    Console.WriteLine(p); 
} 

回答

1
public class A 
{ 
    //Property 
    //must be set somewhere (e.g. constructor) 
    public List<Product> Products { get; private set; } 

    //Method 
    public List<Product> GetProducts() 
    { 
     //return list of products 
    } 
} 

public class B 
{ 
    public void Display() 
    { 
     var a = new A(); 
     foreach (var product in a.Products /*OR a.GetProducts()*/) 
     { 
      Console.WriteLine(product); 
     } 
    } 

} 
+0

您是否建議同時擁有*既*屬性和方法?如果是的話,那就是糟糕的設計,違反了DRY(不要重複自己)原則。 – Kapol

+0

當然不是,我只是把它放在那裏展示可能的方法來解決這個問題。 OP應該做出使用財產或方法的決定。 –

+1

好吧,+1 :-) – Kapol

0

如果您在類中的方法是有一個列表並將其命名爲類似「展示Products()」,併爲Console.WriteLine,並在你的主類調用該方法重複這將是更好的。

+0

喜!是的好吧,我已經這樣做了: public list GetProducts() { return AllProducts; } 但我仍然需要遍歷所有主要的AllProdcuts我不能在其他原因的方法。 – Linexxlol

-1
public List<Product> fillProduct() 
    { 
     List<Product> AllProducts = new List<Product>(); 
     //fill 
    } 
    private void btnAdd_Click(object sender, EventArgs e) 
    { 
     foreach (product p in fillProduct()) 
     { 
      Console.WriteLine(p); 
     } 
    } 

你可以這樣做

相關問題