2013-03-26 49 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>。根据样本数据和问题,我不认为这是你正在寻求的。