Utilizar constructores y destructores

Actualización: noviembre 2007

Los constructores y destructores controlan la creación y destrucción de objetos.

Constructores

Para crear un constructor para una clase, cree un procedimiento denominado Sub New en cualquier parte de la definición de clase. Para crear un constructor parametrizado, especifique los nombres y los tipos de datos de los argumentos de Sub New tal como lo haría en cualquier otro procedimiento, como en el código siguiente:

Sub New(ByVal s As String)

Con frecuencia, los constructores están sobrecargados, como en el código siguiente:

Sub New(ByVal s As String, i As Integer)

Cuando se define una clase derivada de otra, la primera línea del constructor debe ser una llamada al constructor de la clase base, a no ser que ésta tenga un constructor accesible que no requiera parámetros. Por ejemplo, para llamar a la clase base que contiene el constructor anterior, sería MyBase.New(s). En caso contrario, MyBase.New es opcional y el tiempo de ejecución de Visual Basic la llama implícitamente.

Después de escribir el código para llamar al constructor del objeto primario, puede agregar cualquier código de inicialización adicional en el procedimiento Sub New. Sub New puede aceptar argumentos cuando se realiza la llamada como a un constructor con parámetros. Estos parámetros se pasan desde el procedimiento que llama al constructor; por ejemplo, Dim AnObject As New ThisClass(X).

Destructores

El código siguiente muestra cómo utilizar Dispose y Finalize para liberar los recursos de una clase base.

Nota:

Debería seguir las instrucciones para implementar IDisposable incluidas en Duración de los objetos: cómo se crean y destruyen.

    ' Design pattern for a base class.
    Public Class Base
        Implements IDisposable

        ' Keep track of when the object is disposed.
        Protected disposed As Boolean = False

        ' This method disposes the base object's resources.
        Protected Overridable Sub Dispose(ByVal disposing As Boolean)
            If Not Me.disposed Then
                If disposing Then
                    ' Insert code to free managed resources.
                End If
                ' Insert code to free unmanaged resources.
            End If
            Me.disposed = True
        End Sub

#Region " IDisposable Support "
        ' Do not change or add Overridable to these methods.
        ' Put cleanup code in Dispose(ByVal disposing As Boolean).
        Public Sub Dispose() Implements IDisposable.Dispose
            Dispose(True)
            GC.SuppressFinalize(Me)
        End Sub
        Protected Overrides Sub Finalize()
            Dispose(False)
            MyBase.Finalize()
        End Sub
#End Region
    End Class

El código siguiente muestra cómo utilizar Dispose y Finalize para liberar los recursos de una clase derivada.

' Design pattern for a derived class.
Public Class Derived
    Inherits Base

    ' This method disposes the derived object's resources.
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposed Then
            If disposing Then
                ' Insert code to free managed resources.
            End If
            ' Insert code to free unmanaged resources.
        End If
        MyBase.Dispose(disposing)
    End Sub

    ' The derived class does not have a Finalize method
    ' or a Dispose method with parameters because it inherits
    ' them from the base class.
End Class

El código siguiente muestra un modelo de diseño común para el destructor Dispose, utilizando un bloque Using y un bloque Try...Finally equivalente.

Sub DemonstrateUsing()
    Using d As New Derived
        ' Code to use the Derived object goes here.
    End Using
End Sub

Sub DemonstrateTry()
    Dim d As Derived = Nothing
    Try
        d = New Derived
        ' Code to use the Derived object goes here.
    Finally
        ' Call the Dispose method when done, even if there is an exception.
        If Not d Is Nothing Then
            d.Dispose()
        End If
    End Try
End Sub

En el siguiente ejemplo se crea un objeto mediante un constructor con parámetros y se llama a los destructores cuando el objeto deja de ser necesario.

Nota:

Aunque este ejemplo usa Collect para mostrar a qué métodos llama el recolector de elementos no utilizados para eliminar métodos, en general es más conveniente dejar que Common Language Runtime (CLR) administre la recolección de elementos no utilizados.

Sub TestConstructorsAndDestructors()
    ' Demonstrate how the Using statement calls the Dispose method.
    Using AnObject As New ThisClass(6)
        ' Place statements here that use the object.
        MsgBox("The value of ThisProperty after being initialized " & _
        " by the constructor is " & AnObject.ThisProperty & ".")
    End Using

    ' Demonstrate how the garbage collector calls the Finalize method.
    Dim AnObject2 As New ThisClass(6)
    AnObject2 = Nothing
    GC.Collect()
End Sub

Public Class BaseClass
    Sub New()
        MsgBox("BaseClass is initializing with Sub New.")
    End Sub

    Protected Overrides Sub Finalize()
        MsgBox("BaseClass is shutting down with Sub Finalize.")
        ' Place final cleanup tasks here.
        MyBase.Finalize()
    End Sub
End Class

Public Class ThisClass
    Inherits BaseClass
    Implements IDisposable

    Sub New(ByVal SomeValue As Integer)
        ' Call MyBase.New if this is a derived class.
        MyBase.New()
        MsgBox("ThisClass is initializing with Sub New.")
        ' Place initialization statements here. 
        ThisPropertyValue = SomeValue
    End Sub

    Private ThisPropertyValue As Integer
    Property ThisProperty() As Integer
        Get
            CheckIfDisposed()
            ThisProperty = ThisPropertyValue
        End Get
        Set(ByVal Value As Integer)
            CheckIfDisposed()
            ThisPropertyValue = Value
        End Set
    End Property

    Protected Overrides Sub Finalize()
        MsgBox("ThisClass is shutting down with Sub Finalize.")
        Dispose(False)
    End Sub

    ' Do not add Overridable to this method.
    Public Overloads Sub Dispose() Implements IDisposable.Dispose
        MsgBox("ThisClass is shutting down with Sub Dispose.")
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

    Private disposed As Boolean = False
    Public Sub CheckIfDisposed()
        If Me.disposed Then
            Throw New ObjectDisposedException(Me.GetType().ToString, _
            "This object has been disposed.")
        End If
    End Sub

    Protected Overridable Overloads Sub Dispose( _
    ByVal disposing As Boolean)
        MsgBox("ThisClass is shutting down with the Sub Dispose overload.")
        ' Place final cleanup tasks here.
        If Not Me.disposed Then
            If disposing Then
                ' Dispose of any managed resources.
            End If
            ' Dispose of any unmanaged resource.

            ' Call MyBase.Finalize if this is a derived class, 
            ' and the base class does not implement Dispose.
            MyBase.Finalize()
        End If
        Me.disposed = True
    End Sub

End Class

Cuando ejecute este ejemplo, la clase ThisClass llama al constructor Sub New de la clase BaseClass. Una vez que finaliza el constructor de la clase base, la clase ThisClass ejecuta el resto de instrucciones de Sub New que inicializan un valor para la propiedad ThisProperty.

Cuando la clase ya no es necesaria, se llama al destructor Dispose en ThisClass.

Este ejemplo muestra lo siguiente:

BaseClass is initializing with Sub New.

ThisClass is initializing with Sub New.

The value of ThisProperty after being initialized by the constructor is 6.

ThisClass is shutting down with Sub Dispose.

ThisClass is shutting down with the Sub Dispose overload.

BaseClass is shutting down with Sub Finalize.

BaseClass is initializing with Sub New.

ThisClass is initializing with Sub New.

ThisClass is shutting down with Sub Finalize.

ThisClass is shutting down with the Sub Dispose overload.

BaseClass is shutting down with Sub Finalize.

Vea también

Conceptos

Duración de los objetos: cómo se crean y destruyen

Métodos de finalización y destructores

Cómo funcionan los métodos New y Finalize en una jerarquía de clases

Referencia

Dispose