如何在Visual Basic中使用数组或其他设备来用字符串和整数填充表



我正在进行一个项目,该项目涉及到拥有一个字符集合,这些字符都具有不同的属性,我希望将它们放入表中。我已经创建了一个名为Character的类,但我希望能够创建一个数组,其中包含每个属性的名称以及分配给每个属性的整数值。我试图使用嵌套数组来实现这一点,但在创建一个混合了整数和字符串的数组时遇到了问题。在尝试将标签更改为数组中的元素时,它会给我一个例外,即我无法将一维字符串数组转换为字符串。

想法?

如果您使用的是Visual Basic.NET,并且只需要创建字符串/整数对,那么Generic Dictionary就是您需要的结构:

Dim aList As New Generic.Dictionary(Of String, Integer)
aList.Add("Attribute1", 123)
aList.Add("Attribute2", 456)
aList.Add("Attribute3", 789)
Dim iValue As Integer = aList("Attribute2") '456

它是强类型的,值很容易通过它们的键访问。

UPDATE下面是一种更通用的方法,可以为每个给定的键接受不同类型的可变数量的值。此外,它还可以在您需要的类中实现。

首先定义这样一个类:

Public Class MyClass1
  Private m_aMyList As Generic.Dictionary(Of String, ArrayList)
  Public Property MyList As Generic.Dictionary(Of String, ArrayList)
      Get
          Return m_aMyList
      End Get
      Set(ByVal value As Generic.Dictionary(Of String, ArrayList))
          m_aMyList = value
      End Set
  End Property
  Public Sub InitList()
      m_aMyList = New Generic.Dictionary(Of String, ArrayList)
  End Sub
  Public Sub AddValuesToList(i_sKey As String, ParamArray i_aValues() As Object)
      Dim arrList As New ArrayList
      For Each o As Object In i_aValues
          arrList.Add(o)
      Next
      m_aMyList.Add(i_sKey, arrList)
  End Sub
  Public Function GetListByKey(i_sKey As String) As ArrayList
      Return m_aMyList(i_sKey)
  End Function
End Class

它定义了一个保存列表的公共属性和3个方法——初始化列表、向列表添加值和检索值。

当类被这样定义时,你可以这样使用它:

Dim myObj As New MyClass1
myObj.InitList()
myObj.AddValuesToList("Attribute1", 1, "a", 2, 3, "bbb")
myObj.AddValuesToList("Attribute2", "eee", 34, 23, "aqaa")
myObj.AddValuesToList("Attribute3", 1, 2, 3, 4, 5, "qqq")

For Each o In myObj.GetListByKey("Attribute2")
    If TypeOf (o) Is Integer Then
        'perform action on integer values
    ElseIf TypeOf (o) Is String Then
        'perform action on string values
    End If
Next

在本例中,您实例化一个类,初始化列表,用变量混合值向列表中添加3个项,然后保留列表中的第二个项并循环其值。

最新更新