如果我想用 protobuf-net 反序列化它,为什么我必须手动将序列化对象的流位置设置为 0?
我希望 protobuf-net 总是从一开始就读取我的输入流。
如果我想让 protobuf-net 从不同的偏移位置读取我的流(比如通过标签读取类的成员或列表),我会认为这将是一个特殊的用例,我必须处理它有意识地不同(api-wise)。
(我的 protobuf-net 版本是 640。)
这是我的测试用例,它使用继承引发异常:
using System.IO;
using ProtoBuf;
namespace ProtobufStreamTest
{
public class Class1
{
static public void Main(string[] args)
{
var inheritingModel = new InheritingModel()
{
InheritingModelMember1 = "testinheriting",
BaseModelMember1 = 42,
};
var ms = new MemoryStream();
ProtoBuf.Serializer.Serialize(ms, inheritingModel);
var originalStreamPos = ms.Position; // == 33
// ms.Position = 0; // <== works okay, but why do I have to do this? Not setting position = 0 raises InvalidCastException: Unable to cast object of type 'ProtobufStreamTest.BaseModel' to type 'ProtobufStreamTest.InheritingModel'
var deserialized = ProtoBuf.Serializer.Deserialize<InheritingModel>(ms);
ms.Close();
}
}
[ProtoContract]
public class InheritingModel : BaseModel
{
[ProtoMember(4)]
public string InheritingModelMember1 { get; set; }
}
[ProtoContract]
[ProtoInclude(1, typeof(InheritingModel))]
public class BaseModel
{
[ProtoMember(2)]
public int BaseModelMember1 { get; set; }
}
}
此测试用例没有引发异常,不涉及继承,但反序列化对象具有默认(空)值:
using System.IO;
using ProtoBuf;
namespace ProtobufStreamTest
{
public class Class1
{
static public void Main(string[] args)
{
var inheritingModel = new InheritingModel()
{
InheritingModelMember1 = "testinheriting",
};
var ms = new MemoryStream();
ProtoBuf.Serializer.Serialize(ms, inheritingModel);
var originalStreamPos = ms.Position; // == 16
// ms.Position = 0; // works okay, but why do I have to do this? Not setting position to null results in a deserialized object but with null member values
var deserialized = ProtoBuf.Serializer.Deserialize<InheritingModel>(ms);
ms.Close();
}
}
[ProtoContract]
public class InheritingModel
{
[ProtoMember(1)]
public string InheritingModelMember1 { get; set; }
}
}