1

我有两个类 A 和 B。类 B 继承类 A,如下所示。

<ProtoContract()>
Public Class A
    <ProtoMember(1)>
    Public Property ID As Integer
    <ProtoMember(2)>
    Public Property Name() As String = String.Empty
End Class

<ProtoContract()>
Public Class B
    Inherits A
    <ProtoMember(101)>
    Property Title As String = String.Empty
    <ProtoMember(102)>
    Property Status As String = String.Empty
    <ProtoMember(103)>
End Class

当我使用 ProtoBuf 序列化和反序列化 B 类的实例时,A 类的属性值会丢失。在对此进行了一些搜索之后,我想我需要以某种方式在 B 类上使用 ProtoInclude() 标签,但我运气不佳。

示例代码:

 Dim stuff as New B
 With stuff
   .ID = 1
   .Name = "Bob"
   .Title = "Director"
   .Status = "Active"
 End With

 Dim buffer as Byte()
 Dim deserializedStuff as new B

 Using memStream As New IO.MemoryStream
     ProtoBuf.Serializer.Serialize(memStream, stuff)
     buffer = memStream.ToArray
 End Using

 Using memStream As New MemoryStream(buffer)
     memStream.Position = 0  
     deserializedStuff = ProtoBuf.Serializer.Deserialize(Of B)(memStream)
 End Using

此时,“deserializedStuff”上的继承属性值将丢失。它们似乎只是设置为默认值。关于我做错了什么的任何想法?提前致谢。

4

1 回答 1

2

在 A 的 ProtoAttributes 中,您需要指定它也可以包含 B。

<ProtoContract(), ProtoInclude(100, GetType(B))>
Public Class A
    <ProtoMember(1)>
    Public Property ID As Integer
    <ProtoMember(2)>
    Public Property Name() As String = String.Empty
End Class

<ProtoContract()>
Public Class B
    Inherits A
    <ProtoMember(1)>
    Property Title As String = String.Empty
    <ProtoMember(2)>
    Property Status As String = String.Empty
End Class

这是我用来弄清楚你的测试课。

Public Class Test
    Public Sub New()
        Dim stuff As New B With {.ID = 1, .Name = "Bob", .Title = "Director", 
             .Status = "Active"}

        Dim buffer As Byte()
        Using memStream As New IO.MemoryStream
            ProtoBuf.Serializer.Serialize(memStream, stuff)
            buffer = memStream.ToArray
        End Using

        Dim deserializedStuff As B
        Using memStream As New MemoryStream(buffer)
            memStream.Position = 0
            deserializedStuff = ProtoBuf.Serializer.Deserialize(Of B)(memStream)
        End Using

        Debug.Print(deserializedStuff.ID.ToString & "--" & deserializedStuff.Status)
    End Sub
End Class
于 2012-05-30T22:53:29.000 回答