如何序列化自定义对象类型的列表
本文关键字:类型 列表 对象 自定义 序列化 | 更新日期: 2023-09-27 18:36:12
我有这样的类
public class Record
{
public Int32 TotalTrail { get; set; }
public TimeSpan MyTimeSpan { get; set; }
public DateTime MyDateTime { get; set; }
}
我有一个列表来保存它的对象:
List<Record> _records;
然后,当我想序列化列表时:
序列化程序。序列化(流,_records);
上面一行有一个运行时错误:
无法将类型为 System.Collections.Generic.List'1[[SimpleGame.Record, SimpleGame, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] 的对象分配给类型为 SimpleGame.Record 的对象。
是因为无法序列化列表吗?我该如何解决这个问题?
您必须为类型 List<Record>
而不是 Record
创建序列化程序
如果要序列化为 XML,甚至不需要实现可序列化。 下面是将任何对象写入文件的快速简便方法:
Dim s As System.Xml.Serialization.XmlSerializer
Using fs As New IO.FileStream(thePath, FileMode.Create, FileAccess.Write, FileShare.Write)
Using w As System.Xml.XmlTextWriter = New System.Xml.XmlTextWriter(fs, System.Text.Encoding.Default)
s = New System.Xml.Serialization.XmlSerializer(GetType(T))
w.Formatting = Xml.Formatting.Indented
s.Serialize(w, m_objectToSerialize)
End Using
End Using
我认为您需要指定您的对象是 Serializable
,下面是示例。
[Serializable()]
public class Record
{
public Int32 TotalTrail { get; set; }
public TimeSpan MyTimeSpan { get; set; }
public DateTime MyDateTime { get; set; }
}
另一个溶胶
您可以实现ISerializable
接口
public class Record : ISerializable
{
public Int32 TotalTrail { get; set; }
public TimeSpan MyTimeSpan { get; set; }
public DateTime MyDateTime { get; set; }
}
使您的类可序列化...检查此链接。http://msdn.microsoft.com/en-us/library/4abbf6k0.aspx
我遇到了同样的问题:我所做的是,我去了你为其制作列表的类并添加了一个无参数构造函数。我在某处读到序列化适用于无参数构造函数。一旦我这样做了。它就像一个魅力!希望它奏效了..像这样的东西
public class InventoryType
{
public DateTime Date { get; set; }
public int ID { get; set; }
public string RoomT { get; set; }
public int Quantity { get; set; }
public InventoryType() { }
public InventoryType(DateTime date, int id, string roomT, int quantity)
{
this.Date = date;
this.ID = id;
this.RoomT = roomT;
this.Quantity = quantity;
}
public override string ToString()
{
return "Date: " + Date + "'nID: " + ID + "'nRoom Type: " + RoomT + "'nQuantity: " + Quantity;
}
}