2016-04-26 97 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 

所以說:不管問題是什麼,它不會從你的示例代碼顯示。所以下一步就是逐漸引入你的問題的背景,直到它開始破產;那麼你就會知道問題在於你添加的最後一個改變。

相關問題