.Net 序列化
- 将实体转化为流的形式,传递给他人。他人再反序列化就可以得到实体
二进制
var tbLabel = new DataTable("tbLabel");
var ms = new MemoryStream();
tbLabel.Columns.Add("cWorkOrder");
tbLabel.Rows.Add(new[] { "123" });
BinaryFormatter a1 = new BinaryFormatter();
a1.Serialize(ms, tbLabel);
ms.Position = 0;
var dt2 = (DataTable)a1.Deserialize(ms);
XML序列化
var tbLabel = new DataTable("tbLabel");
var ms = new MemoryStream();
tbLabel.Columns.Add("cWorkOrder");
tbLabel.Rows.Add(new[] { "123" });
XmlSerializer a1 = new XmlSerializer(typeof(DataTable));
a1.Serialize(ms, tbLabel);
ms.Position = 0;
var dt2 = (DataTable)a1.Deserialize(ms);
DataContractSerializer
var tbLabel = new DataTable("tbLabel");
var ms = new MemoryStream();
tbLabel.Columns.Add("cWorkOrder");
tbLabel.Rows.Add(new[] { "123" });
DataContractSerializer ser =new DataContractSerializer(typeof(DataTable));
ser.WriteObject(ms,tbLabel);
ms.Position = 0;
var dt2 = (DataTable)ser.ReadObject(ms);
Json序列化
- 不推荐使用,丢失了TableName
- System.Text.Json 序列化容易出错
var tbLabel = new DataTable("tbLabel");
var ms = new MemoryStream();
tbLabel.Columns.Add("cWorkOrder");
tbLabel.Rows.Add(new[] { "123" });
Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
var s= Newtonsoft.Json.JsonConvert.SerializeObject(tbLabel);
var dt2 = Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>(s);
BinaryWriter BinaryReader
- 只能是基元数据类型