Procedura: convertire un'insieme personalizzato in un insieme tipizzato di Visual Basic

Aggiornamento: novembre 2007

In Visual Basic 6.0 è possibile personalizzare gli insiemi in modo da restringerne il contenuto a una sola classe specifica. Un insieme siffatto è anche detto insieme tipizzato. In Visual Basic 2008 sono fornite diverse opzioni per la creazione di classi tipizzate a partire da insiemi personalizzati di Visual Basic 6.0. Nel presente argomento sono descritte tre procedure, ognuna relativa a un'opzione diversa.

In questo argomento si presuppone che l'insieme personalizzato di Visual Basic 6.0 sia stato creato mediante l'utilità Creazione guidata classi. Un insieme di questo tipo presenta i membri elencati di seguito:

  • Add   Consente di aggiungere all'insieme una nuova istanza della classe personalizzata.

  • Item   Restituisce un'istanza dell'insieme in base a un indice contenuto nell'insieme.

  • Count   Restituisce il numero di istanze nell'insieme.

  • Remove   Rimuove un'istanza dall'insieme in base a un indice contenuto nell'insieme.

  • Enumeration   Supporta l'enumerazione mediante la sintassi For Each.

Per utilizzare la procedura di aggiornamento guidato per creare un insieme

  • Aprire il progetto Visual Basic 6.0 in Visual Basic 2008. Di seguito è riportato il codice aggiornato relativo a una classe Forest contenente istanze della classe Tree. Il vantaggio di questo metodo è che non occorre apportare modifiche al codice.

    ' For this example, the Tree class has no members.
    Option Strict Off
    Option Explicit On
    Friend Class Tree
    End Class
    
    Friend Class Forest
      Implements System.Collections.IEnumerable
      'local variable to hold collection
      Private mCol As Collection
    
      Public Function Add(Optional ByRef sKey As String = "") As Tree
        'create a new object
        Dim objNewMember As Tree
        objNewMember = New Tree
        'set the properties passed into the method
        If Len(sKey) = 0 Then
          mCol.Add(objNewMember)
        Else
          mCol.Add(objNewMember, sKey)
        End If
        'return the object created
        Add = objNewMember
        'UPGRADE_NOTE: Object objNewMember may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.MSDNQTR.80.en/commoner/redir/redirect.htm?keyword="vbup1029"'
    
        objNewMember = Nothing
      End Function
    
      Default Public ReadOnly Property Item(ByVal vntIndexKey _
        As Object) As Tree
        Get
          'used when referencing an element in the collection
          'vntIndexKey contains either the Index or Key to the collection,
          'this is why it is declared as a Variant
          'Syntax: Set foo = x.Item(xyz) or Set foo = x.Item(5)
          Item = mCol.Item(vntIndexKey)
        End Get
      End Property
    
      Public ReadOnly Property Count() As Integer
        Get
          'used when retrieving the number of elements in the
          'collection. Syntax: Debug.Print x.Count
          Count = mCol.Count()
        End Get
      End Property
    
      'UPGRADE_NOTE: NewEnum property was commented out. Click for more: 'ms-help://MS.MSDNQTR.80.en/commoner/redir/redirect.htm?keyword="vbup1054"'
    
      'Public ReadOnly Property NewEnum() As stdole.IUnknown
        'Get
          'this property allows you to enumerate
          'this collection with the For...Each syntax
          'NewEnum = mCol._NewEnum
        'End Get
      'End Property
    
      Public Function GetEnumerator() As System.Collections.IEnumerator _
        Implements System.Collections.IEnumerable.GetEnumerator
        'UPGRADE_TODO: Uncomment and change the following line to return the collection enumerator. Click for more: 'ms-help://MS.MSDNQTR.80.en/commoner/redir/redirect.htm?keyword="vbup1055"'
    
        'GetEnumerator = mCol.GetEnumerator
      End Function
    
      Public Sub Remove(ByRef vntIndexKey As Object)
        'used when removing an element from the collection
        'vntIndexKey contains either the Index or Key, which is why
        'it is declared as a Variant
        'Syntax: x.Remove(xyz)
        mCol.Remove(vntIndexKey)
      End Sub
    
      'UPGRADE_NOTE: Class_Initialize was upgraded to Class_Initialize_Renamed. Click for more: 'ms-help://MS.MSDNQTR.80.en/commoner/redir/redirect.htm?keyword="vbup1061"'
    
      Private Sub Class_Initialize_Renamed()
        'creates the collection when this class is created
        mCol = New Collection
      End Sub
      Public Sub New()
        MyBase.New()
        Class_Initialize_Renamed()
      End Sub
    
      'UPGRADE_NOTE: Class_Terminate was upgraded to Class_Terminate_Renamed. Click for more: 'ms-help://MS.MSDNQTR.80.en/commoner/redir/redirect.htm?keyword="vbup1061"'
    
      Private Sub Class_Terminate_Renamed()
        'destroys collection when this class is terminated
        'UPGRADE_NOTE: Object mCol may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.MSDNQTR.80.en/commoner/redir/redirect.htm?keyword="vbup1029"'
    
        mCol = Nothing
      End Sub
      Protected Overrides Sub Finalize()
        Class_Terminate_Renamed()
        MyBase.Finalize()
      End Sub
    End Class
    

.NET Framework e Visual Basic 2008 offrono molti insiemi generici. Il vantaggio di utilizzare classi generiche è che per implementare la classe occorre una quantità di codice minima.

Per creare un insieme utilizzando insiemi generici

  1. Creare la definizione della classe. Di seguito è riportato un esempio di una classe Tree:

    Public Class Tree
        Public Species As String
    End Class
    
  2. Creare una classe elenco generica da .NET Framework. Questa dichiarazione in pratica sostituisce l'intera classe Forest della routine precedente relativa all'utilizzo della procedura di aggiornamento guidato per creare un insieme.

    Dim forest As New System.Collections.Generic.List(Of Tree)
    
  3. Scrivere il codice per accedere all'oggetto elenco. Il codice di seguito riportato aggiunge all'insieme cinque istanze della classe Tree e quindi ne esegue la stampa.

    For count As Integer = 1 To 5
        Dim sapling As New Tree
        sapling.Species = "oak"
        Forest.Add(sapling)
    Next
    
    For Each sapling As Tree In Forest
        MsgBox(sapling.Species)
    Next
    

In .NET Framework è inclusa la classe CollectionBase. Gli insiemi tipizzati sono creati per ereditarietà a partire dalla classe CollectionBase. Questo metodo prevede meno codice rispetto al metodo della procedura di aggiornamento guidato ma più codice rispetto alla soluzione degli insiemi generici. Tuttavia è più flessibile rispetto a quest'ultima soluzione poiché il programmatore può aggiungere altri membri alla classe di insiemi.

Per creare un insieme a partire dalla classe CollectionBase

  1. Creare la definizione della classe. Di seguito è riportato un esempio di una classe Tree:

    Public Class Tree
        Public Species As String
    End Class
    
  2. Creare una classe che erediti dalla classe CollectionBase. Aggiungere almeno un metodo Add e una proprietà Item. In questo modo la classe di insiemi risulta fortemente tipizzata.

    Class TreeCollection
      Inherits System.Collections.CollectionBase
    
      Public Sub Add(ByVal value As Tree)
        Me.List.Add(value)
      End Sub
    
      Default Public Property Item(ByVal index As Integer) As Tree
          Get
              Return CType(Me.List(index), Tree)
          End Get
          Set(ByVal value As Tree)
              If index <= Me.Count - 1 Then
                  Me.List(index) = value
              Else
                  Throw New IndexOutOfRangeException()
              End If
          End Set
      End Property
    End Class
    
  3. Scrivere il codice per accedere all'oggetto elenco. Il codice di seguito riportato aggiunge all'insieme cinque istanze della classe Tree e quindi ne esegue la stampa.

    Dim forest As New TreeCollection
    
    For count As Integer = 1 To 5
        Dim sapling As New Tree
        sapling.Species = "oak"
        Forest.Add(sapling)
    Next
    
    For Each sapling As Tree In Forest
        MsgBox(sapling.Species)
    Next
    

Vedere anche

Riferimenti

List

CollectionBase

IEnumerable