2013-03-26 68 views
0

我有一個測試類,我創建了,我想能夠創建它的多個實例。然後我想用foreach來迭代每個實例。我看過幾個論壇,顯示IEnumerate,但作爲一個非常newbe他們讓我感到困惑。任何人都可以請給我一個新的例子。添加foreach到我的課

我的類:

using System; 
using System.Collections; 
using System.Linq; 
using System.Text 

namespace Test3 
{ 
    class Class1 
    { 
    public string Name { get; set; } 
    public string Address { get; set; } 
    public string City { get; set; } 
    public string State { get; set; } 
    public string Zip  { get; set; } 
    } 
} 

感謝

+1

把每個實例列表 - 那麼你可以做的foreach名單 – Rob 2013-03-26 01:10:24

回答

1

你的類只是一個「數據塊」 - 你需要你的類的多個實例存儲到某種集合類和foreach上使用集合。

0
// Create multiple instances in an array 

Class1[] instances = new Class1[100]; 
for(int i=0;i<instances.Length;i++) instances[i] = new Class1(); 

// Use foreach to iterate through each instance 
foreach(Class1 instance in instances) { 

    DoSomething(instance); 
} 
2

您是否需要枚舉類型的多個實例或創建一個本身可枚舉的類型?

前者很簡單:將實例添加到集合中,例如實現IEnumerable<T>List<T>()

// instantiate a few instances of Class1 
var c1 = new Class1 { Name = "Foo", Address = "Bar" }; 
var c2 = new Class1 { Name = "Baz", Address = "Boz" }; 

// instantiate a collection 
var list = new System.Collections.Generic.List<Class1>(); 

// add the instances 
list.Add(c1); 
list.Add(c2); 

// use foreach to access each item in the collection 
foreach(var item in list){ 
    System.Diagnostics.Debug.WriteLine(item.Name); 
} 

當您使用foreach聲明中,compiler helps out and automatically generatesIEnumerable(如列表)接口所需要的代碼。換句話說,您不需要明確編寫任何附加代碼來遍歷項目。

後者稍微複雜一些,需要自己實施IEnumerable<T>。根據樣本數據和問題,我不認爲這是你正在尋求的。