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

标签 vb.net oop

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

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

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

实体:
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 

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

最佳答案

你可以这样:

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)
希望有帮助!这可以进一步重构,但这应该有效。

关于vb.net - 如何使用 vb.net 创建输出将采用分层结构的父子集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12994592/

相关文章:

asp.net - "Unified Modelling Language"的简单解释,为什么它很重要?

wpf - 页面只能有 Window 或 Frame 作为父级

vb.net - 如何将消失标签编程到 ASP 文本框中?

mysql - 为 Crystal Reports SQL 命令变量赋值

php - 从两个父类继承

javascript - 无法分配这个。对象原型(prototype)中的变量

c# - 如何从 CHM 或 PDF 文件的电子书中读取 ISBN

java - GameManager 类型类的单一职责原则

java - 我不明白我们如何在方法compareTo中使用方法compareTo

c++ - C++中的数据包序列化