2011-04-08 58 views
2

我有一系列属性的一个对象,其自身的一类是:如何创建可迭代的类的集合?

private ClassThing Thing1; 
private ClassThing Thing2; 
private ClassThing Thing3; 

private class ClassThing 
{ 
    public string Name; 
    public int Foos; 
} 

在一些区域I需要能够特异性地访问每个属性,例如:

label1.Text = Thing1.Name; 

然而,还希望创建一个foreach循环来访问每一个,这样的:

string CombinedString; 
foreach(ClassThing Thing in SomeCollection) 
{ 
    CombinedString += Thing.Name; 
} 

最终结果必须是XML可序列化的。这些例子是非常基本的,但我希望他们更容易证明我的需要。

我试着创建这些属性的字典,而不是一个字典不是XML可序列化。我想简单地让一个类的所有属性都可以迭代,但我不知道如何。

任何人都可以指向正确的方向吗?

回答

5

我希望这澄清了一些事情给你,因为我不完全相信,我明白你的问题运行的foreach。

//many normal classes can be made xml serializable by adding [Serializable] at the top of the class 
[Serializable] 
private class ClassThing 
{ 
    public string Name { get; set; } 
    public int Foos { get; set; } 
} 

//here we create the objects so you can access them later individually 
ClassThing thing1 = new ClassThing { Name = "name1", Foos = 1 }; 
ClassThing thing2 = new ClassThing { Name = "name2", Foos = 2 }; 
ClassThing thing3 = new ClassThing { Name = "name3", Foos = 3 }; 

//this is an example of putting them in a list so you can iterate through them later. 
List<ClassThing> listOfThings = new List<ClassThing>(); 
listOfThings.Add(thing1); 
listOfThings.Add(thing2); 
listOfThings.Add(thing3); 

//iteration example 
string combined = string.Empty; 
foreach (ClassThing thing in listOfThings) 
{ 
    combined += thing.Name; 
} 

//you could also have created them directly in the list, if you didnt need to have a reference for them individually, like this: 
listOfThings.Add(new ClassThing { Name = "name4", Foos = 4 }); 

//and more advanced concepts like linq can also help you aggregate your list to make the combined string. the foreach makes the code more readable though. this gives the same result as the foreach above, ignore it if it confuses you :) 
string combined = listOfThings.Aggregate(string.Empty, (current, thing) => current + thing.Name); 

//Here is an example of how you could serialize the list of ClassThing objects into a file: 
using (FileStream fileStream = new FileStream("classthings.xml", FileMode.Create)) 
{ 
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<ClassThing>)); 
    xmlSerializer.Serialize(fileStream, listOfThings); 
} 

为了能够序列使用该方法的对象,它们不能包含一个构造函数,这就是为什么我们使用他们创造的new ClassThing{Name="",Foos=0}方式。

+0

谢谢,很好的例子。 – 2018-02-23 13:54:53

1

您正在寻找IEnumerable接口的实现。有关如何实施它的快速说明,请参见this link

0
public List<ClassThing> Things = new List<ClassThing>(); 

然后你就可以通过。事情

1
class MyClass 
{ 
    private ClassThing Thing1; 
    private ClassThing Thing2; 
    private ClassThing Thing3; 

    internal IEnumerable<ClassThing> GetThings() 
    { 
      yield return Thing1; 
      yield return Thing2; 
      yield return Thing3; 
    } 
    void Test() 
    { 
     foreach(var thing in this.GetThings()) 
     { 
      //use thing 
     } 
    } 
}