如何在列表中访问所需的项目?

时间:2013-03-20 19:09:55

标签: vb.net list collections

我正在将之前的VB6代码转换为.Net(2012),并且正在创建一个包含以前在数组中的数据的类。

Structure defIO
  dim Index as integer
  dim Name as string
  dim State as Boolean
  dim Invert as Boolean
end structure
public IO(128) as defIO

现在我可以访问数组中的每个元素:IO(3).Name =“Trey”

由于我想添加这个阵列结构的一些功能,我创建了一个类。这保存了数据并将在我的类中进行一些操作(如果需要则反转数据等)。然后我创建了类并生成了类的列表。

Public Class clsIO

    Private Shared pState As Boolean
    Private Shared pInvert As Boolean
    Private Shared pIndex As Integer
    Private Shared pName As String

    Public Sub New()
        Try
            pState = False
            pInvert = False
            pIndex = 0

        Catch ex As Exception
            MsgBox("Exception caught!" & vbCrLf & ex.TargetSite.Name & vbCrLf & ex.Message)
        End Try
    End Sub

    Property Name As String
        Get
            Name = pName
        End Get
        Set(value As String)
            pName = value
        End Set
    End Property

    Property State As Boolean
        Get
            State = pState
        End Get
        Set(value As Boolean)
            If pInvert = True Then
                pState = Not value
            Else
                pState = value
            End If
        End Set
    End Property

    Property Invert As Boolean
        Get
            Invert = pInvert
        End Get
        Set(value As Boolean)
            pInvert = value
        End Set
    End Property

    Property Index As Integer
        Get
            Index = pIndex
        End Get
        Set(value As Integer)
            pIndex = value
        End Set
    End Property

    End Class


    DInList.Add(New clsIO() With {.Index = 0, .Name = "T1ShutterInPos", .Invert = False, .State = False})
    DInList.Add(New clsIO() With {.Index = 1, .Name = "T2ShutterInPos", .Invert = False, .State = False})
    DInList.Add(New clsIO() With {.Index = 2, .Name = "T3ShutterInPos", .Invert = False, .State = False})
    DInList.Add(New clsIO() With {.Index = 3, .Name = "RotationPos1", .Invert = False, .State = False})
    DInList.Add(New clsIO() With {.Index = 4, .Name = "RotationPos2", .Invert = False, .State = False})
    DInList.Add(New clsIO() With {.Index = 5, .Name = "RotationPos3", .Invert = False, .State = False})

现在我想访问列表中的特定元素:

DInList(1).Name = "Test"

这不起作用。我不知道如何访问列表中的特定元素而不循环遍历列表中的所有项目。

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

从类变量声明中删除Shared关键字。您将它们定义为类变量,因此该类的每​​个实例都没有自己的副本。这意味着最后一次更新会覆盖前一次更新,并且更改该类的任何对象都会影响它们。