0

假设我有这样的课程:

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次按钮......

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

4

1 回答 1

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

现在,要对您制作的第三辆车做点什么,请参考 Cars(3):

Cars(3).Make = "Kia"
Cars(3).Color = "Blue"
于 2013-09-26T18:03:09.597 回答