堆栈溢出的堆栈溢出

时间:2011-10-20 08:37:16

标签: vb.net types recursion

我想知道是否可以让父类实例化子类的对象,而不进行无限递归。

考虑这个例子:

Module Module1
    Sub Main()
        Dim _baseFruit As New Fruit
        _baseFruit.Write()

        Console.ReadKey()
    End Sub
End Module

Public Class Fruit
    Public Property Type As String
    Public Property BaseType As String
    Public Property FruitType As New Apple

    Sub New()
        Type = "Fruit"
        BaseType = "N/A"
    End Sub

    Public Sub Write()
        Console.WriteLine("Type: {0} BaseType: {1} FruitType: {2} ", Type, BaseType, FruitType.Type)
    End Sub
End Class

Public Class Apple
    Inherits Fruit

    Public Sub New()
        Me.Type = "Apple"
    End Sub
End Class

只要Apple被实例化,它就会进入无限递归。

说这不可能是不正确的,那就是在父母中引用一个孩子也是基础?

编辑:从下面的答案我已经更新了代码,瞧,它有效。

Module Module1
    Sub Main()
        Dim _baseFruit As New Fruit
        Dim _apple As New Apple

        _baseFruit.Write(_apple)
        Console.ReadKey()
    End Sub
End Module

Public Class Fruit
    Public Property Type As String
    Public Property BaseType As String
    Public Property FruitChildInstance As Apple

    Sub New()
        Type = "Fruit"
        BaseType = "N/A"
    End Sub

    Public Sub Write(ByVal fruit As Apple)
        FruitChildInstance = fruit
        Console.WriteLine("Type: {0} BaseType: {1} FruitType: {2} ", Type, BaseType, FruitChildInstance.Type)
    End Sub
End Class

Public Class Apple
    Inherits Fruit

    Public Sub New()
        Me.Type = "Apple"
    End Sub
End Class

1 个答案:

答案 0 :(得分:1)

这可以称为“无限型”。如果允许将成员变量留空,则不一定会出现问题。

如果不查看此代码的实际含义,您可以这样说:

指示FruitType成员必须是Apple实例会导致无限量的对象嵌套。让它未初始化(Dim FruitType as Fruit)将毫无问题。

现在当你时考虑语义:

您将“类型”概念与“实例”概念混合在一起:Fruit实例具有一种类型(例如 Apple),但它是让它成为一名水果成员也很奇怪。

如果您将此建模为类FruitType,其中Fruit的成员标注为FruitType,那么无限递归就不会发生。