Share via


생성자 및 소멸자 사용

업데이트: 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

다음 코드에서는 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

다음 예제에서는 매개 변수화된 생성자를 사용하여 개체를 만들고 개체가 더 이상 필요하지 않을 때 소멸자를 호출합니다.

참고:

이 예제에서는 Collect를 사용하여 가비지 수집기가 메서드를 삭제할 때 호출하는 메서드를 보여 주지만 일반적으로 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 클래스는 ThisProperty 속성의 값을 초기화하는 Sub New의 나머지 문을 실행합니다.

해당 클래스가 더 이상 필요하지 않으면 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