ProtoBuf-Net:没有为类型定义的序列化程序:System.Object

时间:2016-04-26 14:54:16

标签: c# serialization protobuf-net protocol-buffers

我正在序列化一个只存储属性的对象。  它有父继承,但我确保序列化属性与数字具有不同的索引。

[ProtoContract]
[ProtoInclude(597, typeof(DesiredProto))]
[ProtoInclude(598, typeof(RandomClass1Proto))]
[ProtoInclude(599, typeof(RandomClass2Proto))]
[ProtoInclude(600, typeof(RandomClass3Proto))]
public class BaseProto
{
   protected string mName = "";
   protected string mOwner = "";
   protected VObjectType mVType; //this is an enumeration!
   public BaseProto(){}

  [ProtoMember(1)]
  public String Name
  {
     get { return mName; }
     set { mName = value;}
  }

  [ProtoMember(2)]
  public String Owner
  {
     get { return mOwner; }
     set { mOwner = value;}
  }

  [ProtoMember(3)]
  public VObjectType VType
  {
     get { return mVType; }
     set { mVType = value;}
  }
}

然后DesiredProto:

 [ProtoContract]
public class DesiredProto : BaseProto
{
  protected DestinationType mDestType;
  protected string mAddress = "";

  public DesiredProto()
  {
  }

  [ProtoMember(1)]
  public DestinationType DestType //this is an enumeration
  {
     get { return mDestType; }
     set { mDestType = value;}
  }

  [ProtoMember(2)]
  public String Address
  {
     get { return mAddress; }
     set { mAddress = value;}
  }
 }

现在真正奇怪的部分是序列化似乎完全正常。每当我对这个“DesiredProto”进行序列化和反序列化时,如果我忽略错误,它就可以工作。 最后,这不是这些类的完整代码片段,它们要长得多,但希望错误以某种方式包含在其中。

1 个答案:

答案 0 :(得分:1)

在这里工作正常:

using ProtoBuf;
using System;

class Program
{
    static void Main()
    {
        BaseProto obj = new DesiredProto
        {
            Address = "123 Somewhere",
            DestType = DestinationType.Foo,
            Name = "Marc",
            Owner = "Also Marc",
            VType = VObjectType.A
        };
        BaseProto clone = Serializer.DeepClone(obj);
        DesiredProto typedClone = (DesiredProto)clone;
        Console.WriteLine(typedClone.Address);
        Console.WriteLine(typedClone.DestType);
        Console.WriteLine(typedClone.Name);
        Console.WriteLine(typedClone.Owner);
        Console.WriteLine(typedClone.VType);
    }
}

public enum DestinationType { Foo } // I just made a guess here
public enum VObjectType // you said this is an enum
{
    A, B, C
}
class RandomClass1Proto : BaseProto { } // just a dummy type to make it complile
class RandomClass2Proto : BaseProto { }
class RandomClass3Proto : BaseProto { }

// omitted: code from the question here

所以:无论问题是什么,它都不会从您的示例代码中显示出来。所以下一步是逐步介绍你的问题的背景,直到它开始破裂;然后你会知道问题出在你添加的最后一次更改中。