让我们说,我有一个包含对象的类。
namespace Class_Serialization
{
[Serializable]
public class Data
{
public string Name = "Example1";
public string place = "Torino";
public DateTime time = DateTime.Now;
}
}
我正在尝试使用ISerialization接口
序列化它[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.Exception {System.Runtime.Serialization.SerializationException}
答案 0 :(得分:4)
如果您正在实施ISerializable
,则需要签名的构造函数:
protected YourType(SerializationInfo information, StreamingContext context) {}
加载数据(基本上是GetObjectData
的反向)。据推测,(未经测试):
StreamThisData = (Data)info.GetValue("Object Data", typeof(Data));
答案 1 :(得分:1)
尝试添加构造函数:
protected SerializeThisClass(SerializationInfo info, StreamingContext context)
{
}
http://msdn.microsoft.com/en-us/library/ms182343(v=vs.80).aspx