簡體   English   中英

序列化派生的 class 時,不包括 ProtoBuf.net 基礎 class 屬性

[英]ProtoBuf.net Base class properties is not included when serializing derived class

使用 ProtoBuf.net 的最新 2.0 beta 版本我正在嘗試序列化派生類(只是示例),我得到空文件。 為什么基礎 class 屬性未序列化?

[ProtoContract]
[Serializable]
public class Web2PdfClient : Web2PdfEntity
{

}

[ProtoContract]
[Serializable]
public class Web2PdfEntity : EngineEntity
{

    [ProtoMember(1)]
    public string Title { get; set; }
    [ProtoMember(2)]
    public string CUrl { get; set; }
    [ProtoMember(3)]
    public string FileName { get; set; }

}


[ProtoContract]
[Serializable]
public class EngineEntity
{

    public bool Result { get; set; }
    public string ErrorMessage { get; set; }
    public bool IsMembershipActive { get; set; }
    public int ConversionTimeout { get; set; }
    public byte[] FileStorage { get; set; }
}

在使用下面的代碼序列化 class 時,我得到空文件。

var Web2PDF = new Web2PdfClient
                          {                                
                              CUrl = "http://www.google.com",
                              FileName = "test.txt"
                          };
        using (var file = File.Create(@"C:\Users\Administrator\Projects\temp\test.bin"))
        {
            Serializer.Serialize(file, Web2PDF);

        }

實際上,我很驚訝沒有拋出異常 - 我會調查,為了讓它工作。 基本類型必須有一個唯一的方式來指示每個子類型,這可以通過屬性來指定。 或(在 v2 中)在運行時:例如:

[ProtoContract]
[Serializable]
public class Web2PdfClient : Web2PdfEntity
{

}

[ProtoContract]
[ProtoInclude(7, typeof(Web2PdfClient))]
[Serializable]
public class Web2PdfEntity : EngineEntity
{ ... }

7沒有什么特別之處,只是它不應該與為該類型定義的任何其他成員發生沖突。 可以定義多個子類型(使用不同的標簽)。 另請注意,protobuf-net 不查看[Serializable] ,因此除非您還使用BinaryFormatter (或類似的),否則您不需要它。

類似地, EngineEntity應該宣傳預期的子類型,並且應該指出要序列化的成員(以及針對哪個標簽)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM