我有这堂课:
[Serializable]
class Data
{
int data1;
int data2;
Other_Data[] array;
}
class Other_Data
{
// I have some ints and bool here
}
问题是如何使用单个文件序列化/反序列化Data类型的对象
答案 0 :(得分:1)
如果类型Other_Data
也可序列化,那么这应该没有问题。只要知道序列化程序需要公开类型和属性或字段:
[Serializable]
public class Data
{
public int data1;
public int data2;
public Other_Data[] array;
}
[Serializable]
public class Other_Data
{
public int someInt;
public bool someBool;
}
然后例如使用XmlSerializer:
var obj = new Data() {
data1 = 5,
data2 = 7,
array = new Other_Data[] {
new Other_Data() { someInt = 1, someBool = true },
new Other_Data() { someInt = 2, someBool = true },
new Other_Data() { someInt = 3, someBool = false }
}
};
var xmlSerializer = new XmlSerializer(typeof(Data));
var stringWriter = new StringWriter();
xmlSerializer.Serialize(stringWriter, obj);
Console.WriteLine(stringWriter.ToString());