如何使用vb.net创建输出将采用分层结构的父子集合

时间:2012-10-21 03:12:01

标签: vb.net oop

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

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

我为parentchild1child2subchild1subchild2创建了实体类和集合类。我需要将父集合类实例传递给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 

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

1 个答案:

答案 0 :(得分:0)

你可以这样做

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.Emplyees.Add(employee1)

希望有所帮助!这可以进一步重构,但我应该这样做。