我在去年夏末开始学习VBA,我可以自豪地说,这是我第一次在Google上找不到答案。这周我开始自学关于课程的知识,我遇到了一种情况,我希望能够为我的课程识别一个“索引属性”。
由于这可能不是最清楚的解释,这里有一个假设的例子:
我为我的超级棒三明治店(clsSASS)创建的类包含卡路里、重量(克)、价格和配料的属性。前三个是带有非常简单的let和get语句的变量。即:
Public pCal As Integer
Public Property Get Calories() As Integer
Calories= pCal
End Property
Public Property Let Calories(Value As Integer)
pCal = Value
End Property然而,配料被设计为按输入顺序包含配料列表。我最初的直觉是这样做的:
Public pIngd As Collection
Public Property Get Ingredients(Value As Integer) As Collection
Ingredients = pIngd(Value)
End Property
Public Property Set Ingredients(Object As Collection)
Set pIngd = Object
End Property因此,如果培根是列表中的第一种配料(老实说,它一直都是),像clsNewSandwich.Ingredients(1)这样的东西将返回字符串' Bacon‘。
当我将容器属性添加到一个类中,然后又不知道如何识别容器中的各个项时,问题就出现了。因此,这可能只是一个简单的语法问题,与类无关。
非常感谢!
*为清晰/连续而编辑
发布于 2013-06-06 04:24:01
好的--我将收回我关于总是命名let/set并获得相同名称的建议,因为在这种情况下你不能这样做,因为"input“和"output”类型是不同的。因此,在下面的示例中,我将返回一个配料的属性命名为Ingredient
“clsSASS”类:
Dim pIngd As Collection
Property Set Ingredients(c As Collection)
Set pIngd = c
End Property
Property Get Ingredient(v As Integer) As String
Ingredient = pIngd(v)
End Property常规模块:
Sub Tester()
Dim c As New Collection
Dim s As New clsSASS
c.Add "bacon"
c.Add "lettuce"
c.Add "tomato"
Set s.Ingredients = c
Debug.Print s.Ingredient(1) 'bacon
Debug.Print s.Ingredient(2) 'lettuce
Debug.Print s.Ingredient(3) 'tomato
End Subhttps://stackoverflow.com/questions/16947849
复制相似问题