gpt4 book ai didi

c# - 从 MemoryStream() 反序列化

转载 作者:太空宇宙 更新时间:2023-11-03 20:29:34 27 4
gpt4 key购买 nike

比方说,我有一个包含对象的类。

namespace Class_Serialization
{
[Serializable]
public class Data
{
public string Name = "Example1";
public string place = "Torino";
public DateTime time = DateTime.Now;
}
}

我正在尝试使用 ISerialization 接口(interface)对其进行序列化

[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}

最佳答案

如果你正在实现ISerializable,你需要一个签名的构造函数:

protected YourType(SerializationInfo information, StreamingContext context) {}

加载数据(基本上是 GetObjectData 的逆过程)。据推测,与(未经测试):

StreamThisData = (Data)info.GetValue("Object Data", typeof(Data));

关于c# - 从 MemoryStream() 反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8211492/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com