跳轉到內容

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
華夏公益教科書