修改类的特定实例 [英] Modify an Specific instance of class

查看:24
本文介绍了修改类的特定实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的类:

Lets suppose i have a class like so:

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

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

and i have a button that does the following:

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

and i press the button like 10 times...

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

How can i modify an specific instance of this class (like, the one created when i clicked the button for the third time) to modify its properties?

推荐答案

您的 Stuff 实例仅存在于 Button 单击事件中.为了给它更大/更长的 Scope 你需要在别处声明它:

Your Stuff instance only exists inside the Button click event. To give it larger/longer Scope you need to declare it elsewhere:

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

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

To make multiples for every click, you need some sort of collection to store them

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):

Now, to do something to the third car you made, reference Cars(3):

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

这篇关于修改类的特定实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆