使用构造函数和析构函数
更新: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 类将运行 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.