每当我尝试创建一个新的CD对象时,我都会遇到堆栈溢出.我想将一个参数传递给mediaFactory,以便确定创建了什么类型的媒体.任何人都可以指出为什么我这样做时可能遇到问题“Dim media As CD = New CD()”
谢谢
Public MustInherit Class MediaFactory
Inherits MediaContext
Implements IMedia
Public Sub New(ByVal typeId As Integer)
MyBase.new()
_mediaTypeId = typeId
End Sub
Private _mediaTypeId As Integer
Public Property mediaTypeId() As Integer Implements IMedia.mediaTypeId
Get
Return _mediaTypeId
End Get
Set(ByVal value As Integer)
_mediaTypeId = value
End Set
End Property
End Class
Public Class CD
Inherits MediaFactory
Implements IMedia
Public Sub New()
MyBase.New(1)
End Sub
Public Sub New(ByVal name As String)
MyBase.New(1)
MyBase.title = name
End Sub
End Class
Public Class MediaContext
Private Shared _strategies As New Dictionary(Of MediaEnum, IMedia)()
Public Sub New()
_strategies.Add(MediaEnum.CD, New CD())
End Sub
Public Sub New(ByVal name As String)
_title = name
End Sub
Private _title As String
Public Property title() As String
Get
Return _title
End Get
Set(ByVal value As String)
_title = value
End Set
End Property
End Class
最佳答案 在无限递归的情况下发生堆栈溢出.当你有方法调用时会发生这种情况:
Public Sub B()
A()
End Sub
Public Sub A()
B()
End Sub
然后调用A()或B().调用堆栈的大小(跟踪当前正在运行的子站点,以及调用它的子站点,依此类推到程序的主站点)会无限增长,直到达到可用空间的限制. (它看起来像A> B> A> B> A> B ……等)
在你的情况下,似乎你的New()方法调用New(1),它反过来调用MediaFactory的New(整数),调用.new(),它调用你工厂的New()…希望你得到的图片.