共用方式為


使用建構函式和解構函式

更新:2007 年 11 月

建構函式和解構函式控制物件的建立與解構。

建構函式

若要建立類別的建構函式,要先在類別定義中的任意處,建立名為 Sub New 的程序。若要建立參數型建構函式,應將引數的名稱和資料型別指定給 Sub New,正如您為其他任何程序指定引數一般,如下列程式碼所示:

Sub New(ByVal s As String)

通常建構函式都是多載,如下列程式碼所示:

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

當您定義衍生自另一類別的類別時,建構函式的第一行必須呼叫基底類別的建構函式,除非基底類別含有不帶有任何參數的可存取建構函式。例如,呼叫包含上述建構函式的基底類別可以是 MyBase.New(s)。否則,MyBase.New 為選擇項,而且 Visual Basic 執行階段會隱含地呼叫它。

撰寫呼叫父物件建構函式的程式碼之後,您可以將任何額外的初始化程式碼加入至 Sub New 程序。以參數化建構函式呼叫 Sub New 時,它可以接受引數。這些參數會從呼叫建構函式的程序傳遞過來,例如 Dim AnObject As New ThisClass(X)。

解構函式

下列程式碼將顯示如何使用 Dispose 和 Finalize,釋放基底類別中的資源。

注意事項:

您應該遵循在物件存留期:物件的建立和終結中開始實作 IDisposable 的方針。

    ' 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

下列程式碼將顯示如何使用 Dispose 和 Finalize,釋放衍生類別中的資源。

' 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

下列程式碼將顯示 Dispose 解構函式的通用設計模式,這個模式會使用 Using 區塊和對等用法的 Try...Finally 區塊。

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

以下範例會使用參數型建構函式建立物件,然後當物件不再需要時呼叫解構函式。

注意事項:

雖然這個範例會使用 Collect,示範記憶體回收行程將呼叫哪些方法,以用於處置 (Dispose) 方法,但是通常您應該讓 Common Language Runtime (CLR) 管理記憶體回收。

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

當您執行此範例時,ThisClass 類別會呼叫 BaseClass 類別的 Sub New 建構函式。在完成基底類別中的建構函式之後,類別 ThisClass 會執行 Sub New 中剩餘的陳述式,初始化屬性 ThisProperty 的值。

不再需要這個類別時,會在 ThisClass 中呼叫 Dispose 解構函式。

這個範例會顯示下列項目:

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.

請參閱

概念

物件存留期:物件的建立和終結

Finalize 方法和解構函式

類別階層架構中的 New 和 Finalize 方法如何運作

參考

Dispose