[英]How to serialise generic list?
我有一个通用的employees
和supervisors
名单
List<Employee> employees = new List<Employee>();
List<Supervisor> supervisors = new List<Supervisor>();
他们都是我标记为[Serializable]
的employee
类别的一部分
我可以将这两个列表放到另一个列表中,以便更轻松地进行序列化吗?
我看过序列化教程,但它们仅指定一个或更少的通用列表。
我已经提供了一个模板,我想单击“保存”按钮并完成序列化过程,最好将两个列表都放入一个更大的列表中。
private void btnSave_Click(object sender, EventArgs e)
{
FileStream outFile;
BinaryFormatter bFormatter = new BinaryFormatter();
}
您实际上可以将两个列表序列化为一个流:
using (FileStream fs = new FileStream(..., FileMode.OpenOrCreate)) {
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, employees);
bf.Serialize(fs, supervisors);
}
BinaryFormatter
为数据块添加元数据前缀,这显然也使它可以将数据连接到一个文件。 为了回读supervisors
您必须先加载其他列表。 由于列表不是固定长度的记录,因此当您重写第一个列表并将其丢失在孤立数据之后或覆盖其中的一部分时,第二个列表可能变得不可用。
由于有太多的事情可以阻止它起作用,因此很容易为倍数创建“ holder”或容器类:
[Serializable()]
public class BFHolder
{
public List<Employee> employees { get; set; }
public List<Supervisor> supervisors { get; set; }
public BFHolder()
{
}
}
反序列化后,可以根据需要拉出列表。
还有一个更好的选择是ProtoBuf-Net (向下滚动至自述)。 除了比BinaryFormatter更快并创建较小的输出外,它还包括将多个对象序列化为一个流的方法。
using (FileStream fs = new FileStream(..., FileMode.OpenOrCreate)) {
Serializer.SerializeWithLengthPrefix<List<Employee>>(fs, employees,
PrefixStyle.Base128);
Serializer.SerializeWithLengthPrefix<List<Supervisor>>(fs, supervisors,
PrefixStyle.Base128);
}
您可以将此列表放在另一个类容器中并对其进行序列化/反序列化。
[Serializable]
public class Container
{
public List<Employee> employees = new List<Employee>();
public List<Supervisor> supervisors = new List<Supervisor>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.