如何序列化/反序列化通用的手动滚动接口集合

时间:2011-08-16 05:00:34

标签: .net xml-serialization datacontractserializer

我知道你不能序列化一个接口,但是为了讨论的目的,在Interface和Domain Data类之间有一对一的映射,所以我假设/希望有一种方法告诉序列化器使用域类在看到给定的接口时。

我有一个相当简单的层次结构对象结构

  • 个人资料<标准课程
    • 元素<手卷集接口类:节点(IProfile)
      • 元素<标准班级
    • 研究<手卷集类:节点(Of IStudy)
      • 研究<标准班级

Elements集合的声明如下:

Public Class Elements
   Inherits Domain.Nodes(Of Domain.IElement)
   Implements Domain.IElements

    Public Sub New()
        MyBase.New()
    End Sub

    Public Sub New(ByVal pItems As IEnumerable(Of Domain.IElement))
        MyBase.New(pItems)
    End Sub

End Class

由于其他原因,我不是从List(Of T)或键控集合或任何东西继承,Nodes是手动集合,但是我在Nodes(Of T)基类中实现IEnumerable(Of T)。 / p>

所以我试图尽可能地减少序列化/反序列化为XML。我被引导使用<DataContract()><CollectionDataContract()><DataMember()>但我愿意考虑其他选项。

我的反序列化功能目前看起来像:

Private Shared Function Deserialize(ByVal pFilePath As String) As Domain.IProfile
    Dim lNewItem As Domain.IProfile
    Dim lProfileSerializer As New System.Xml.Serialization.XmlSerializer(GetType(Domain.Profile))
    lNewItem = CType(lProfileSerializer.Deserialize(Store.OpenFile(pFilePath, IO.FileMode.Open)), Domain.Profile)
    Return lNewItem
End Function

那你怎么建议我接近这个?是否有一个简单的属性我可以用来对CollectionDataContract说“将子类创建为'元素'”...

1 个答案:

答案 0 :(得分:0)

我还没有做过很多关于XML序列化的事情,但我认为你还需要将Serializable属性添加到你的Class等等。请注意,虽然某些属性无法应用于该属性。

请参阅产品:&gt;&GT;

http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx

<Serializable()> _
Public Class ExampleClass

End Class
相关问题