我对二进制文件的反序列化结构有疑问。我的结构有另一个结构作为属性:
[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);
}
}
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.Deserialize 的异常并且反序列化失败。
Frequency not found.
流不是空的,我检查了这个。
感谢您的任何想法。