2016-04-26 66 views
1

我正在序列化一个只有属性被存储的对象。 它有一个父继承,但我确保序列化的属性与数字具有不同的索引。ProtoBuf-Net:没有为类型定义的序列化程序:System.Object

[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”,它就会起作用,如果我忽略这个错误。 最后,这不是这些类的完整代码片段,它们要长得多,但希望错误包含在这里。

+0

什么是'DestinationType'? –

+0

信息的次要事情,但如果您使用的是C#的最新版本,您可能想要使用自动实现的属性 - 它们可以节省大量的信息;例如:'[ProtoMember(2)] public string Address {get; set;}' - 编译器基本上和你一样*(在幕后),但没有错别字的风险(使用错误字段等) –

+0

DestinationType是一个枚举! – jStaff

回答

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 

所以说:不管问题是什么,它不会从你的示例代码显示。所以下一步就是逐渐引入你的问题的背景,直到它开始破产;那么你就会知道问题在于你添加的最后一个改变。

相关问题