尽管初始化了默认值,但类属性仍然为空,并让属性被使用

问题描述 投票:0回答:1

我使用 property let 和 rightafter 使用 property get ,该值是空的,尽管无论如何类初始化都有一个默认值。我不明白为什么它是空的。

内置调试。打印返回“0 0 6”

在评论的 debug.print 中,我有语法错误,顺便说一下,我不知道为什么。

主副

Option Explicit
Public oClass1 As Class1

Sub main()

Set oClass1 = New Class1

Call oClass1.CreateSubClass

'Debug.Print oClass1.oClass2.sum2(oClass2.p_paramX1, oClass2.p_paramX2)

End Sub

1级

Option Explicit
Public oClass2 As Class2

Private Sub Class_Initialize()
End Sub

Sub CreateSubClass()

Set oClass2 = New Class2

oClass2.p_paramX1 = 5
oClass2.p_paramX2 = 5

Debug.Print oClass2.p_paramX1 'return 0

Debug.Print oClass2.sum2(oClass2.p_paramX1, oClass2.p_paramX2) 'return 0
Debug.Print oClass2.sum2(3, 3) 'return 6

End Sub

2级

Private Sub Class_Initialize()

Dim paramX1 As Integer
Dim paramX2 As Integer

paramX1 = 1
paramX2 = 2

End Sub
Public Function sum2(X1, X2)
     sum2 = X1 + X2
End Function

Public Property Get p_paramX1() As Integer
    p_paramX1 = paramX1
End Property

Public Property Let p_paramX1(value As Integer)
    paramX1 = value
End Property

Public Property Get p_paramX2() As Integer
    p_paramX2 = paramX2
End Property

Public Property Let p_paramX2(value As Integer)
    paramX2 = value
End Property

excel vba class
1个回答
0
投票

将声明从初始化移至选项显式并且有效。根据蒂姆·威廉姆斯的评论。

Option Explicit
Private paramX1 As Integer
Private paramX2 As Integer

Private Sub Class_Initialize()

paramX1 = 1
paramX2 = 2


End Sub
Public Function sum2(X1, X2)

sum2 = X1 + X2

End Function

Public Property Get p_paramX1() As Integer
    p_paramX1 = paramX1
End Property

Public Property Let p_paramX1(value As Integer)
    paramX1 = value
End Property

Public Property Get p_paramX2() As Integer
    p_paramX2 = paramX2
End Property

Public Property Let p_paramX2(value As Integer)
    paramX2 = value
End Property

对于提到的语法错误,正确的调用应该包括完整的类链。

    Debug.Print oClass1.oClass2.sum2(oClass1.oClass2.p_paramX1, oClass1.oClass2.p_paramX2)
© www.soinside.com 2019 - 2024. All rights reserved.