实例化父类中的元素

发布于 2024-12-04 05:26:14 字数 486 浏览 1 评论 0原文

我有以下结构:

-PARENT

--CHILD

--CHILD

--CHILD

--CHILD

非常简单。现在,我需要 PARENT 类具有诸如 createNewChild(id) 之类的函数。 PARENT 元素具有每个 CHILD 必须覆盖的以下内容:

Public MustOverride Function getId() As Integer

现在,是否可以在运行时获取父元素的所有可用子元素的列表,以便我可以执行此操作?抱歉,如果这听起来令人困惑,我很难解释这一点。

基本上,我希望能够执行以下操作:

Dim nParent as PARENT = PARENT.createNewChild(5)

有什么想法吗?我正在使用 VB.net,因此任何 .net 答案都是可以接受的。谢谢!

I have the following structure:

-PARENT

--CHILD

--CHILD

--CHILD

--CHILD

Pretty straight forward. Now, I need the PARENT class to have a function such as createNewChild(id). The PARENT element has the following that each CHILD must override:

Public MustOverride Function getId() As Integer

Now, is it possible to get a list of all available children of a parent at run time so that I can do this? Sorry if this sounds confusing, I'm having a hard time explaining this.

Basically though, I want to be able to do the following:

Dim nParent as PARENT = PARENT.createNewChild(5)

Any ideas? I'm using VB.net so any .net answers are acceptable. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

与之呼应 2024-12-11 05:26:14

好吧,我唯一能想到的跟踪父类的子类的方法就是在创建时创建一个子类列表。

Class Parent
    Private Shared childList As New List(Of Child)()

    Public Sub CreateNewChild(id As Integer)
        Dim newChild As New Child(id)
        childList.Add(newChild)
        Return newChild
     End Sub

   Public Overridable Function GetID() As Integer
       Return 0
   End Function

   Public Shared Function GetAllChildren() As List(Of Child)
       Return childList
   End Function
End Class

Class Child Inherits Parent
    Private m_ID As Integer
    Public Property ID() As Integer
    Get
        Return m_ID
    End Get
    Set
        m_ID = Value
     End Set
End Property

Private Sub New(id As Integer)
    Me.ID = id
End Sub
End Class

抱歉,代码是我最初用 C# 编写的,然后使用在线转换器将其转换为 VB。

Well, the only thing that I could think of to keep track of the children of your parent class is by creating a list of children upon creation.

Class Parent
    Private Shared childList As New List(Of Child)()

    Public Sub CreateNewChild(id As Integer)
        Dim newChild As New Child(id)
        childList.Add(newChild)
        Return newChild
     End Sub

   Public Overridable Function GetID() As Integer
       Return 0
   End Function

   Public Shared Function GetAllChildren() As List(Of Child)
       Return childList
   End Function
End Class

Class Child Inherits Parent
    Private m_ID As Integer
    Public Property ID() As Integer
    Get
        Return m_ID
    End Get
    Set
        m_ID = Value
     End Set
End Property

Private Sub New(id As Integer)
    Me.ID = id
End Sub
End Class

Sorry about the code, I originally wrote it in C# and used an online converter to convert to VB.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文