跳转到内容

Visual Basic .NET/IDisposable

来自,自由的教科书

IDisposable 接口

[编辑 | 编辑源代码]

当对象需要在使用后“清理”时,会实现 IDisposable 接口。如果对象具有“Dispose”方法,则需要在使用后清理它。

清理此类对象最简单的方法是使用 VB 关键字“Using”。

    Using f As New Form
        f.Show
    End Using

当 IDisposable 对象是表单级别变量时,应在 Form_Closed 事件中对其进行处理。

    Public Class Form1
        Private mfrmChild As Form
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            mfrmChild = New Form
            mfrmChild.Text = "Child"
            mfrmChild.Show()
        End Sub
        Private Sub frmMain_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
            mfrmChild.Dispose()
        End Sub
    End Class
华夏公益教科书