XmlSerializer不复制嵌套的类值

时间:2015-04-23 14:45:35

标签: vb.net xmlserializer deep-copy

我使用XmlSerializer对一个对象进行DeepCopy,但不知何故它不会复制嵌套属性。

<TestClass()>
Public Class ObjectClonerTest
    ReadOnly _target As IObjectCloner = New ObjectCloner()

    <TestMethod()>
    Public Sub DeepCopy_ComplexSourceObject_NestedObjectCopied()
        Dim source As New SerialisableComplexGenericParameterHelper()
        source.Data() = 1
        source.ComplexValue.Data() = 2

        Dim actual = _target.DeepCopy(source)

        Assert.AreEqual(1, actual.Data())
        Assert.AreEqual(2, actual.ComplexValue.Data())
    End Sub

    Public Class SerialisableComplexGenericParameterHelper
        Public Property Data() As Integer
        Public ReadOnly ComplexValue As New SerialisableGenericParameterHelper()
    End Class

    Public Class SerialisableGenericParameterHelper
        Public Property Data() As Integer
    End Class

End Class

复制功能:

Public Function DeepCopy(Of T)(ByVal pSource As T) As T Implements IObjectCloner.DeepCopy
    Using memoryStream As New MemoryStream()
        Dim binaryFormatter As New XmlSerializer(GetType(T))

        binaryFormatter.Serialize(memoryStream, pSource)

        memoryStream.Position() = 0

        Return DirectCast(binaryFormatter.Deserialize(memoryStream), T)
    End Using
End Function

2 个答案:

答案 0 :(得分:1)

XmlSerializer不会序列化ReadOnly字段。删除ReadOnly解决了这个问题。

答案 1 :(得分:0)

ComplexValue声明为:

Public ReadOnly ComplexValue As New SerialisableGenericParameterHelper()

这不是一个属性 - 它只是一个字段。解决这个问题应该按照我的想法进行排序。