可以說,我有一個類中有對象。從MemoryStream反序列化()
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());
}
Error: $exception{"The constructor to deserialize an object of type 'Class_Serialization.SerializeThisClass' was not found."} System.Exception {System.Runtime.Serialization.SerializationException}
嘗試做這種方式http://stackoverflow.com/questions/5017274/c-sharp-binaryformatter-and-deserialization-complex-objects –
坦率地說,因爲所有你正在做的是添加一個單一的元素,我會試圖刪除'ISerializable'並讓'BinaryFormatter'自動處理它。 –