1
我想知道如果我可以讓父類實例化一個子類的對象,而無需進入無限遞歸。只要蘋果被實例化堆棧溢出堆棧溢出
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
,它進入無限遞歸:
考慮這個例子。
說這是不可能的,這是不正確的,那就是有一個孩子在父母也是基地引用?
編輯:從下面的答案我已經更新了代碼,你看,它的工作原理。
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
非常有說服力,容易理解。我會更新課程來解釋這一點。當然我會爭辯說,如果你這樣做,你可能需要重新思考你的實現,但從來不是一個糟糕的設計陷阱的好例子。 – deanvmc