修改类的特定实例

时间:2013-09-26 17:26:57

标签: vb.net

假设我有一个类似的课程:

Public Class Car

Private _id As Integer

Public Sub New()

End Sub

Public Property ID As Integer
    Get
        Return _id
    End Get
    Set(ByVal value As Integer)
        _id = value
    End Set
End Property
End Class

我有一个执行以下操作的按钮:

   Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    Dim Stuff As New Car
    'Other code..

End Sub

然后按下按钮10次......

如何修改此类的特定实例(例如,第三次单击按钮时创建的实例)以修改其属性?

1 个答案:

答案 0 :(得分:2)

您的Stuff实例仅存在于Button click事件中。为了给它更大/更长Scope,你需要在其他地方声明它:

Dim Stuff As Car            ' what it is

Private Sub Button2_Click(...
  Stuff = New Car     ' actual instancing/creation of Stuff of Type Car
  'Other code..

End Sub

要为每次点击制作倍数,您需要某种集合来存储它们

Dim Cars As New List(Of Car)         ' many other collections will work
Dim CarItem As Car                   ' car instances to put in it

Private Sub Button2_Click(... 
  CarItem = New Car     ' instance of Type Car

  Cars.Add(CarItem)

End Sub

现在,要对你制造的第三辆车做点什么,请参考汽车(3):

Cars(3).Make = "Kia"
Cars(3).Color = "Blue"