コンストラクタとデストラクタの使用方法

更新 : 2007 年 11 月

コンストラクタとデストラクタは、オブジェクトの構築と破棄を制御します。

コンストラクタ

クラスのコンストラクタを作成するには、クラス定義の任意の場所に Sub New というプロシージャを作成します。パラメータ化されたコンストラクタを作成するには、他のプロシージャと同じように、Sub New への引数の名前とデータ型を指定します。次に、コード例を示します。

Sub New(ByVal s As String)

コンストラクタは、次のコードに示すように、オーバーロードされる場合があります。

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

パラメータを受け取らないコンストラクタに基本クラスからアクセス可能な場合を除き、他のクラスから派生したクラスを定義するときには、コンストラクタの 1 行目で基本クラスのコンストラクタを呼び出す必要があります。上のコンストラクタを持つ基本クラスの呼び出しは、MyBase.New(s) のようになります。それ以外の場合、MyBase.New は省略可能で、Visual Basic のランタイムが暗黙的に呼び出します。

親オブジェクトのコンストラクタを呼び出すコードを記述したら、Sub New プロシージャに初期化コードを自由に追加できます。Sub New はパラメータ化されたコンストラクタとして呼び出されると、引数を受け取ることができます。これらのパラメータは、コンストラクタを呼び出すプロシージャから渡されます。たとえば、Dim AnObject As New ThisClass(X) のように指定します。

デストラクタ

Dispose と Finalize を使用して基本クラスのリソースを解放する方法は、次のコードのようになります。

2z08e49e.alert_note(ja-jp,VS.90).gifメモ :

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

次のコードは、同じ機能を持つ Using ブロックと Try...Finally ブロックを使用して、Dispose デストラクタに共通するデザイン パターンを示しています。

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

次の例では、パラメータ化されたコンストラクタを使用してオブジェクトを作成し、オブジェクトが不要になったときにデストラクタを呼び出しています。

2z08e49e.alert_note(ja-jp,VS.90).gifメモ :

この例では、ガベージ コレクタがどのメソッドを呼び出してメソッドを破棄するかを示すために Collect を使用していますが、通常は共通言語ランタイム (CLR: Common Language Runtime) がガベージ コレクションを管理します。

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