我想知道我是否可以让父类实例化一个子类的对象,而不是进入无限递归。
考虑这个例子:
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发布于 2011-10-20 16:59:44
这可以被称为“无限类型”。如果允许成员变量保留为空,这不一定是问题。
不看这段代码的实际含义,您可以这样说:
规定FruitType成员必须是Apple实例会导致无限数量的对象嵌套。将其保留为未初始化(Dim FruitType as Fruit)不会造成任何问题。
现在,当您将语义考虑在内时:
你把“类型”的概念和“实例”的概念混在一起了:一个水果实例有一个类型(比如Apple类),但是让它有一个Fruit成员也是很奇怪的。
如果您将其建模为一个类FruitType,其中一个Fruit具有一个维度为FruitType的成员,那么无限递归就不会发生。
https://stackoverflow.com/questions/7833168
复制相似问题