Object.Finalize 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
允許物件在記憶體回收進行回收之前,嘗試釋放資源並執行其他清除作業。
!Object ()
~Object ();
abstract member Finalize : unit -> unit
override this.Finalize : unit -> unit
Finalize ()
範例
下列範例會 Finalize 驗證方法在覆寫 Finalize 被終結時呼叫。 請注意,在生產應用程式中, Finalize 系統會覆寫 方法,以釋放 物件所持有的 Unmanaged 資源。 另請注意,C# 範例會提供解構函式,而不是覆寫 Finalize 方法。
using System;
using System.Diagnostics;
public class ExampleClass
{
Stopwatch sw;
public ExampleClass()
{
sw = Stopwatch.StartNew();
Console.WriteLine("Instantiated object");
}
public void ShowDuration()
{
Console.WriteLine("This instance of {0} has been in existence for {1}",
this, sw.Elapsed);
}
~ExampleClass()
{
Console.WriteLine("Finalizing object");
sw.Stop();
Console.WriteLine("This instance of {0} has been in existence for {1}",
this, sw.Elapsed);
}
}
public class Demo
{
public static void Main()
{
ExampleClass ex = new ExampleClass();
ex.ShowDuration();
}
}
// The example displays output like the following:
// Instantiated object
// This instance of ExampleClass has been in existence for 00:00:00.0011060
// Finalizing object
// This instance of ExampleClass has been in existence for 00:00:00.0036294
open System.Diagnostics
type ExampleClass() =
let sw = Stopwatch.StartNew()
do
printfn "Instantiated object"
member this.ShowDuration() =
printfn $"This instance of {this} has been in existence for {sw.Elapsed}"
override this.Finalize() =
printfn "Finalizing object"
sw.Stop()
printfn $"This instance of {this} has been in existence for {sw.Elapsed}"
let ex = ExampleClass()
ex.ShowDuration()
// The example displays output like the following:
// Instantiated object
// This instance of ExampleClass has been in existence for 00:00:00.0011060
// Finalizing object
// This instance of ExampleClass has been in existence for 00:00:00.0036294
Imports System.Diagnostics
Public Class ExampleClass
Dim sw As StopWatch
Public Sub New()
sw = Stopwatch.StartNew()
Console.WriteLine("Instantiated object")
End Sub
Public Sub ShowDuration()
Console.WriteLine("This instance of {0} has been in existence for {1}",
Me, sw.Elapsed)
End Sub
Protected Overrides Sub Finalize()
Console.WriteLine("Finalizing object")
sw.Stop()
Console.WriteLine("This instance of {0} has been in existence for {1}",
Me, sw.Elapsed)
End Sub
End Class
Module Demo
Public Sub Main()
Dim ex As New ExampleClass()
ex.ShowDuration()
End Sub
End Module
' The example displays output like the following:
' Instantiated object
' This instance of ExampleClass has been in existence for 00:00:00.0011060
' Finalizing object
' This instance of ExampleClass has been in existence for 00:00:00.0036294
如需覆寫 Finalize 方法的其他範例,請參閱 GC.SuppressFinalize 方法。
備註
如需此 API 的詳細資訊,請參閱 Object.Finalize 補充 API 備註。