【发布时间】:2016-09-27 03:44:59
【问题描述】:
protobuf-net v2.1.0 ( latest available as NuGet package )
Visual Studio 2015 v14
C#
我没有使用 protogen.exe 从消息类型定义生成我的类
因为我有额外的要求,所以我编写了自己的生成器,它编写了以下类:
[Serializable]
public partial class MyType: ProtoBuf.IExtensible
{
[ProtoBuf.ProtoMember(1, IsRequired = false, Name = @"RegistrationDate", DataFormat = ProtoBuf.DataFormat.Default)]
[System.ComponentModel.DefaultValue("1/1/0001 12:00:00 AM")]
public DateTime RegistrationDate;
[ProtoBuf.ProtoMember(2, IsRequired = false, Name = @"RegistrationId", DataFormat = ProtoBuf.DataFormat.TwosComplement)]
[System.ComponentModel.DefaultValue(null)]
public long? RegistrationId;
但是当我尝试序列化时:
var myObject = new MyType(RegistrationDate="2016-01-01",RegistrationId=1);
var stream = new MemoryStream();
ProtoBuf.Serializer.Serialize(stream, myObject );
protobuf-net 抛出异常:
“System.InvalidOperationException”类型的异常发生在 protobuf-net.dll 但未在用户代码中处理
附加信息:类型不是预期的,没有合同可以 推断:MyNamespace.MyType
显然protobuf-net 期望类声明用原型合同属性装饰:
[Serializable]
[ProtoBuf.ProtoContract(Name=@"MyTypeProto")]
public partial class MyType: ProtoBuf.IExtensible
{
但是,由于我使用诸如 DateTime 和 int? 之类的类型,我不相信我可以创建兼容的 proto2 消息类型。
如何构造我的类以便protobuf-net 可以成功序列化?
更新:如果我添加 [Protobuf.ProtoContract] 属性,那么我可以序列化/反序列化而不会引发异常,但我的反序列化对象丢失了所有值(所有字段均为 null):
[Serializable]
[Protobuf.ProtoContract]
public partial class MyType: ProtoBuf.IExtensible
{
[ProtoBuf.ProtoMember(1, IsRequired = false, Name = @"RegistrationDate", DataFormat = ProtoBuf.DataFormat.Default)]
[System.ComponentModel.DefaultValue("1/1/0001 12:00:00 AM")]
public DateTime RegistrationDate;
[ProtoBuf.ProtoMember(2, IsRequired = false, Name = @"RegistrationId", DataFormat = ProtoBuf.DataFormat.TwosComplement)]
[System.ComponentModel.DefaultValue(null)]
public long? RegistrationId;
var myObject = new MyType(RegistrationDate="2016-01-01",RegistrationId=1);
var stream = new MemoryStream();
ProtoBuf.Serializer.Serialize(stream, myObject );
var deserialized = ProtoBuf.Serializer.Deserialize<MyType>(stream);
// deserialized.RegistrationDate is null
// deserialized.RegistrationId is null
【问题讨论】:
标签: c# protobuf-net