我有一个自定义类,声明没有New,就像是New一样。为什么?我该如何防止这种情况?我做错了什么?
在注明的代码"问题在这里",pPolice将在检查时被实例化,就像它在类的顶部用New声明一样。这意味着pPolice永远不会是Nothing,因此永远不会输入If块,并且pPolice永远不会按照我想要的方式实例化。
此代码是一个简化的模型来说明问题。
自定义类clsPeople模拟集合(在实践中强类型化)。
Private pPeople as Collection
Private Sub Class_Initialize()
Set pPeople = New Collection
End Sub
Public Sub Add(Name as String)
pPeople.Add Name
End Sub
Public Property Get Count() as Integer
Count = pPeople.Count
End Property
' Other collection-like functions here...
自定义类clsCivilServants有不同的人群。
Private pPolice as clsPeople
'Private pFire as clsPeople ' Listed to show how the class might work
Private Sub Class_Initialize()
Set pPolice = New clsPeople
End Sub
Public Sub ResetPolice()
Set pPolice = Nothing
End Sub
Public Property Get Police() as clsPeople
If pPolice is Nothing Then ' <---------- Problem Here
Set pPolice = New clsPeople
pPolice.Add "Officer Joe" ' Example to show that init worked
End If
Set Police = pPolice
End Property
Dim Springfield as clsCivilServants
Set Springfield = New clsCivilServants
' Step 1
' look at pPolice: Declared, 0 people
' Step 2
Springfield.Police.Add "Officer Mike"
' look at pPolice: Declared, 1 person
' Step 3
Springfield.ResetPolice
' look at pPolice: Nothing, N/A
' Step 4
Debug.Print Springfield.Police.Count
' observing Police causes declaration of pPolice
' look at pPolice: Declared, 1 person
' Step 5
Springfield.Police.Add "Officer Tom"
' look at pPolice: Declared, 2 people
答案 0 :(得分:0)
问题似乎只在某些调试情况下才会发生。
Springfield.Police
列在VBA监视窗格中。我真的不确定为什么会这样,但当然简单的解决办法是避免这种情况。如果我了解更多,会更新此答案。