我如何将类的方法应用于类的属性?

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

我有一个包含字符串属性ClsAnimal的类species,还有一个方法plural,该方法只返回在字符串末尾添加了“ s”的字符串。我想知道是否可以直接将.Plural应用于Animal.Species,如下例所示:

Sub Test()
    Dim Animal As New ClsAnimal

    Animal.Species = "cat"

    debug.print Animal.Species
    'expected result "cat"

    debug.print Animal.Species.Plural
    'expected result "cats"

End Sub

[ClsAnimal Code:

Option Explicit

Private PSpecies As String

Property Let Species(val As String)
    PSpecies = val
End Property

Property Get Species() As String
    Species = PSpecies
End Property


'returns the name of an animal + "s"
Private Function Plural(val) As String
    Plural = val & "s"
End Function
vba
1个回答
0
投票

您可以以某种方式破解您描述的想要的行为。我实现它们的方式是创建一个“扩展”字符串的新类。我叫我的StringExt,它看起来像这样:

Option Explicit
Private pValue As String

'@DefaultMember
Public Property Get Value() As String
    Value = pValue
End Property

Public Property Let Value(val As String)
    pValue = val
End Property

Public Function Pluralize() As String
    Dim suffix As String

    'Examine last letter of the string value...
    Select Case LCase(Right(pValue, 1))
    Case "" 'empty string
        suffix = ""
    Case "s" 'words that end in s are pluralized by "es"
        suffix = "es"

    'Test for any other special cases you want...

    Case Else ' default case
        suffix = "s"
    End Select

    Pluralize = pValue & suffix
End Function

这是一个包装器类,它包装内部字符串值。它具有单个方法,该方法将尝试返回多个内部字符串值。这里要注意的一件事是DefaultMember的使用。我使用了一个非常方便的vba编辑器COM插件RubberDuck,使用Default Member为我完成了所有幕后工作。您可以手动进行操作。您需要导出类模块并在文本编辑器中对其进行修改,并在属性getter中添加Attribute Value.VB_UserMemId = 0标签:

...
Public Property Get Value() As String
Attribute Value.VB_UserMemId = 0
    Value = pValue
End Property

Public Property Let Value(val As String)
    pValue = val
End Property
...

然后,将模块导入回您的vba项目。此属性在vba编辑器中不可见。有关默认成员here的更多信息,但它基本上意味着,如果未指定任何属性,则将返回此属性。

接下来,我们对Species属性使用新的StringExt类型,稍微改变一下动物类别:

Option Explicit

Private pSpecies As StringExt

Public Property Set Species(val As StringExt)
    Set pSpecies = val
End Property

Public Property Get Species() As StringExt
    Set Species = pSpecies
End Property

Private Sub Class_Initialize()
    Set pSpecies = New StringExt
End Sub

请注意,由于现在是对象类型,因此现在需要确保实例化pSpecies字段。我在Initializer类中执行此操作以确保它始终发生。

现在,您的客户代码应该可以正常工作。

Sub ClientCode()
    Dim myAnimal As Animal

    Set myAnimal = New Animal
    myAnimal.Species = ""

    Debug.Print myAnimal.Species.Pluralize
End Sub

Disclamer:

在某些边缘情况下,用基本的字符串类型替换对象类型可能会导致意外的行为。您最好只使用一些带有字符串参数并返回复数形式的全局字符串帮助器方法。但是,我的实现将获得您在此问题中要求的行为。 :-)

© www.soinside.com 2019 - 2024. All rights reserved.