从MemoryStream()反序列化
本文关键字:反序列化 MemoryStream | 更新日期: 2023-09-27 18:15:14
假设我有一个类,里面有对象
namespace Class_Serialization
{
[Serializable]
public class Data
{
public string Name = "Example1";
public string place = "Torino";
public DateTime time = DateTime.Now;
}
}
我正在尝试使用序列化接口
来序列化它[Serializable]
public class SerializeThisClass : ISerializable
{
public Data StreamThisData;
public SerializeThisClass()
{
}
public SerializeThisClass(Data _StreamThisData)
{
StreamThisData = _StreamThisData;
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Object Data", StreamThisData);
}
}
现在,当我用下面的代码序列化
时Data DataToSerialize = new Data();
BinaryFormatter DataToBinary = new BinaryFormatter();
SerializeThisClass serialize = new SerializeThisClass(DataToSerialize);
SerializeIn SerializeInMem = new SerializeIn();
DataToBinary.Serialize(SerializeInMem.StreamOfData, serialize);
ListOfStreams.Add(SerializeInMem);
它正常序列化,但是当我试图反序列化它时,它给了我错误
BinaryFormatter BinaryToData = new BinaryFormatter();
foreach (SerializeIn x in ListOfStreams)
{
x.StreamOfData.Position = 0;
SerializeThisClass DeserializeData = (SerializeThisClass)BinaryToData.Deserialize(x.StreamOfData);
MessageBox.Show("Name: " + DeserializeData.StreamThisData.Name + "'nPlace: " + DeserializeData.StreamThisData.place + "'nDateTime: " + DeserializeData.StreamThisData.time.ToString());
}
错误:$exception{"反序列化类型对象的构造函数"Class_Serialization。没有找到SerializeThisClass。"}系统。异常{System.Runtime.Serialization.SerializationException}
如果您正在实现ISerializable
,则需要签名的构造函数:
protected YourType(SerializationInfo information, StreamingContext context) {}
加载数据(基本上与GetObjectData
相反)。大概,使用(未测试):
StreamThisData = (Data)info.GetValue("Object Data", typeof(Data));
尝试添加构造函数:
protected SerializeThisClass(SerializationInfo info, StreamingContext context)
{
}
http://msdn.microsoft.com/en-us/library/ms182343 (v = vs.80) . aspx