4

我想在 VB.NET 中创建一个层次结构,如下所示

<Parent>
  <Child1><Child1 />
  <Child2>
     <Subchild1 />
     <Subchild2 />
<Child2 />     
</Parent>

parent我为、child1child2和.创建了实体类和集合subchild1subchild2。我需要将父集合类实例传递给 XML 序列化程序类,以生成上面给出的分层节点结构。我不知道该怎么做。请给我一个样品。

实体:

Public class Parent
  Public property FirstName as string
  Public property LastName as string
End Class

Public Class Child1
  Public property Color as string
End class

Public Class Child2
  Public property Color as string
End class

Public Class SubChild1
  Public property FirstName as string
End Class

Public Class SubChild2
  Public property FirstName as string
End Class

Collection Class:
Public class ParentS
  Public Function Add(objrow as Parent, byref skey as object) as Parent 

我是否需要将子类作为属性添加到父类?如何做到这一点并创建一个如上所述的结构。请帮忙。谢谢。

4

1 回答 1

1

你可以这样:

Public Class Node

  Public Property FirstName As String
  Public Property LastName As String

  Private _childNodes As New List(Of Node)

  Public Property ChildNodes As List(Of Node)
  Get
     Return _childNodes
  End Get
  Set
     _childNodes = value
  End
  End Property

End Class

用法

Dim parent As New Node
parent.FirstName = "John"
parent.LastName = "Doe"

Dim child_1 As New Node()
child_1.FirstName = "Jane"
child_1.LastName = "Doe"
parent.ChildNodes.Add(child_1)

更新

Public Class Employee

  Public Property FirstName As String
  Public Property LastName As String

End Class

Public Class Department

  Private _employees As New List(Of Employee)
  Private _subDepartments As New List(Of Department)

  Public Property SubDepartments As List(Of Department)
  Get
     Return _subDepartments
  End Get
  Set
     _subDepartments = value
  End
  End Property

  Public Property Employees As List(Of Employee)
  Get
     Return _employees
  End Get
  Set
     _employees = value
  End
  End Property

End Class

用法

Dim dept As New Department
dept.Name  = "Accounting"

Dim subDept1 As New Department()
subDept1.Name = "Audit"

dept.SubDepartments.Add(subDept1)

Dim employee1 As New Employee()
employee1.FirstName = "John"
employee1.LastName = "Doe"

dept.Employees.Add(employee1)

希望有帮助!这可以进一步重构,但这应该可以工作。

于 2012-10-21T08:15:55.457 回答