解决方法到VB.Net 2003 System.Collections.Generic?

时间:2013-08-22 14:32:44

标签: vb.net .net-1.1

我正在使用旧的Web应用程序(vb.net 2003),我正在尝试使用自定义类的通用列表。

我意识到根据link

在.Net 2中引入了System.Collections.Generic

列表有替代品吗?例如,一个类的数组?

假设我有以下类定义:

Public Class Box
  Public x As Integer
  Public y As Integer
End Class

一个Class Box数组:

Dim BoxList() As Box
BoxList(0).x = 1
BoxList(0).y = 1

BoxList(1).x = 2
BoxList(2).y = 2

但是BoxList(0).x = 1错误:Object reference not set to an instance of an object

时出现错误

我只是在这里猜测。

2 个答案:

答案 0 :(得分:4)

使用ArrayList,如下所示:

Dim BoxList As New ArrayList
Dim box = New Box()
box.x = 1
box.y = 2
BoxList.Add(box)

注意:建议您将Box类添加一个构造函数,该类将接受xy值,如下所示:

Public Class Box
    Public x As Integer
    Public y As Integer

    Public Sub New(ByVal _x As Integer, ByVal _y As Integer)
        x = _x
        y = _y
    End Sub
End Class

现在,您可以将ArrayList代码缩短为:

Dim BoxList As New ArrayList
BoxList.Add(New Box(1, 2))

要使用ArrayList中的值,您需要取消ArrayList中的值,以取消({1}}的值,如下所示:

For Each box In BoxList
    ' Use x value, like this
    CType(box, Box).x
Next

OR(如Meta-Knight建议的那样)

For Each box As Box In BoxList
    ' Now box is typed as Box and not object, so just use it
    box.x
Next

答案 1 :(得分:1)

您可以创建自己的自定义集合类 - 这是我们在泛型之前必须做的事情。 This article from MSDN为您提供了具体信息:

''' Code copied directly from article
Public Class WidgetCollection
   Inherits System.Collections.CollectionBase

    Public Sub Add(ByVal awidget As Widget)
       List.Add(aWidget)
    End Sub
    Public Sub Remove(ByVal index as Integer)
       If index > Count - 1 Or index < 0 Then
          System.Windows.Forms.MessageBox.Show("Index not valid!")
       Else
          List.RemoveAt(index)
       End If
    End Sub
    Public ReadOnly Property Item(ByVal index as Integer) As Widget
       Get
          Return CType(List.Item(index), Widget)
       End Get
    End Property

End Class