从二进制文件反序列化具有结构成员的类
本文关键字:成员 结构 二进制文件 反序列化 | 更新日期: 2023-09-27 18:36:14
我对二进制文件的反序列化结构有问题。我的结构体有另一个结构作为属性:
[Serializable()]
public struct Record : ISerializable
{
public SensorInfo SensorInfo;
public List<short[]> Frames;
public Record(SerializationInfo info, StreamingContext ctxt)
{
this.Frames = (List<short[]>)info.GetValue("Frames", typeof(List<short[]>));
this.SensorInfo = (SensorInfo)info.GetValue("SensorInfo", typeof(SensorInfo));
}
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("Frames", this.Frames);
info.AddValue("SensorInfo", this.SensorInfo);
}
}
传感器信息结构:
[Serializable]
public struct SensorInfo : ISerializable
{
public double Frequency;
public int FramePixelDataLength;
public int FrameWidth;
public int FrameHeight;
public SensorInfo(SerializationInfo info, StreamingContext ctxt)
{
this.Frequency = (double)info.GetValue("Frequency", typeof(double));
this.FramePixelDataLength = (int)info.GetValue("FramePixelDataLength", typeof(int));
this.FrameWidth = (int)info.GetValue("FrameWidth", typeof(int));
this.FrameHeight = (int)info.GetValue("FrameHeight", typeof(int));
}
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("Frequency ", this.Frequency);
info.AddValue("FramePixelDataLength ", this.FramePixelDataLength);
info.AddValue("FrameWidth", this.FrameWidth);
info.AddValue("FrameHeight", this.FrameHeight);
}
}
我正在使用以下代码使用序列化程序:
static public class RecordSerializer
{
static RecordSerializer()
{
}
public static void SerializeRecord(string filename, Record recordToSerialize)
{
Stream stream = File.Open(filename, FileMode.Create);
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, recordToSerialize);
stream.Close();
}
public static Record DeSerializeRecord(string filename)
{
Record recordToSerialize;
Stream stream = File.Open(filename, FileMode.Open);
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
recordToSerialize = (Record)bFormatter.Deserialize(stream);
stream.Close();
return recordToSerialize;
}
}
序列化工作正常,我得到一个输出文件。但是当我尝试反序列化它时,我只收到来自 bFormatter.反序列化和反序列化失败的异常。
Frequency not found.
流不为空,我检查了这个。
感谢您的任何想法。
您正在为属性Frequency
和FramePixelDataLength
添加一个空格,例如"频率"和"帧像素数据长度"。
使用这个:
info.AddValue("Frequency", this.Frequency);
info.AddValue("FramePixelDataLength", this.FramePixelDataLength);
而不是:
info.AddValue("Frequency ", this.Frequency);
info.AddValue("FramePixelDataLength ", this.FramePixelDataLength);