JYe*_*ton 2 c# iteration serialization
我有一个对象的一系列属性,它们本身就是一个类:
private ClassThing Thing1;
private ClassThing Thing2;
private ClassThing Thing3;
private class ClassThing
{
public string Name;
public int Foos;
}
Run Code Online (Sandbox Code Playgroud)
在某些领域,我需要能够专门访问每个属性,例如:
label1.Text = Thing1.Name;
Run Code Online (Sandbox Code Playgroud)
但是,还需要创建一个foreach循环来访问每个循环,如下所示:
string CombinedString;
foreach(ClassThing Thing in SomeCollection)
{
CombinedString += Thing.Name;
}
Run Code Online (Sandbox Code Playgroud)
最终结果必须是XML可序列化的.这些例子非常基础,但我希望它们更容易证明我的需要.
我尝试创建这些属性的字典,但字典不是XML可序列化的.我想简单地让所有这些属性的成员本身可以迭代,但我不知道如何.
谁能指出我正确的方向?
我希望这能为你澄清一些事情,因为我不完全确定我理解你的问题.
//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);
}
Run Code Online (Sandbox Code Playgroud)
为了能够使用此方法序列化对象,它们不能包含构造函数,这就是我们使用new ClassThing{Name="",Foos=0}创建它们的方式.
| 归档时间: |
|
| 查看次数: |
11668 次 |
| 最近记录: |