我正在编写一个项目,将一个对象从父应用程序传递到子应用程序。我使用Protobuf对数据进行序列化和反序列化。我还使用非持久化内存映射文件进行写入(序列化时)和读取(反序列化时)。以下是代码:
[ProtoContract(SkipConstructor = true)]
public class Test
{
[ProtoMember(1)]
public int ID { get; private set; }
[ProtoMember(2)]
public bool TestBool { get; private set; }
[ProtoMember(3)]
public string MessageBody { get; private set; }
public Test(int id, bool testBool, string messageBody)
{
this.ID = id;
this.TestBool = testBool;
this.MessageBody = messageBody;
}
public void Serialize()
{
MemoryMappedFile mmf = MemoryMappedFile.CreateNew("testmap", 1000);
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
Serializer.SerializeWithLengthPrefix(stream, this, PrefixStyle.Base128);
stream.Flush();
}
}
public static Test Deserialize()
{
using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("testmap"))
{
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
return Serializer.DeserializeWithLengthPrefix<Test>(stream, PrefixStyle.Base128);
}
}
}
}
//On the parent application
var msg = new SharedLibrary.Test(1234, true, "Test message hahah");
msg.Serialize();
//spawn child application
//On the child application
Test result = Test.Deserialize();
当我运行这段代码时,调用Serializer.Deserialize函数会出现以下错误:
Exception thrown: 'ProtoBuf.ProtoException' in protobuf-net.dll
Additional information: Invalid field in source data: 0
我认为这个错误是因为流比实际数据要大而导致的。当反序列化流时,我认为它开始读取超出实际数据范围的内容。
同时,还有另一个错误:
Exception thrown: 'ProtoBuf.ProtoException' in protobuf-net.dll
Additional information: No parameterless constructor found for Test
我不确定最好的解决方法是什么。是否有一种读取流字节直到没有数据剩余并停止读取的方法?如果没有,我可以用其他方法解决吗?
set
属性是私有的?使用Attributes
可能表明使用了反射。 - Jeroen van Langen