更好的oop练习:类函数的参数

时间:2017-08-31 15:11:15

标签: vba excel-vba oop object

假设我有一个这样的类:它有namesurname作为属性,以及一个msgbox数据的函数。我应该使用此功能的第一个变体还是第二个?

Private name As String
Private surname As String

Function do_something_1() As String
     MsgBox("Hello, " & name & " " & surname)
     do_something_1 = name & " " & surname
End Function

Function do_something_2(name As String, surname As String) As String
     MsgBox("Hello, " & name & " " & surname)
     do_something_2 = name & " " & surname
End Function

如果是第二个函数,namesurname参数会重载类属性吗?假设类属性是JohnGreen,而函数是使用JackBlack来调用的,这将是msgbox?

编辑:我知道在第一个版本中,属性也可以通过getter访问,但我不想在这里使用它。

1 个答案:

答案 0 :(得分:0)

这是代码在属性中的外观(如注释中所述)。该类名为clsHuman

Option Explicit

Private m_sName As String
Private m_sSurname As String

Public Property Get Name() As String

    Name = m_sName

End Property

Public Property Get Surname() As String

    Surname = m_sSurname

End Property

Public Property Let Surname(ByVal sNewValue As String)

    m_sSurname = sNewValue

End Property

Public Property Let Name(ByVal sNewValue As String)

    m_sName = sNewValue

End Property

Function do_something_1() As String

    MsgBox ("Hello, " & Name & " " & Surname)
    do_something_1 = Name & " " & Surname

End Function

Function do_something_2(myName As String, mySurname As String) As String

    MsgBox ("Hello, " & myName & " " & mySurname)
    do_something_2 = myName & " " & mySurname

End Function

有了这个课程,你可以从这样的模块中调用它:

Option Explicit

Public Sub TestMe()

    Dim objHuman As New clsHuman

    objHuman.Name = "Vit"
    objHuman.Surname = "yata"

    Debug.Print objHuman.do_something_1
    Debug.Print objHuman.do_something_2("V", "D")

End Sub

如您所见,do_something_1向msgbox显示了该类中对象的名称,而do_something_2显示了带参数的msgbox。

编辑: 关于这个问题: 假设类属性是John和Green,而函数是用Jack和Black调用的,这将是msgboxed?答案是Jack和Black。但这些属性将保留John和Green。