2

私は古い Web アプリケーション (vb.net 2003) で作業しており、カスタム クラスの汎用リストを使用しようとしています。

リンクによると、System.Collections.Genericが.Net 2で導入されたことに気付きました

リストに代わるものはありますか?たとえば、クラスの配列?

次のクラス定義があるとします。

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

クラスボックスの配列:

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

私はここで推測しています。

4

2 に答える 2

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

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

または(メタナイトが提案したように)

For Each box As Box In BoxList
    ' Now box is typed as Box and not object, so just use it
    box.x
Next
于 2013-08-22T14:35:28.150 に答える
1

独自のカスタム コレクション クラスを作成できます。これは、ジェネリックの前に行う必要があったことです。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
于 2013-08-22T14:44:10.317 に答える