错误:不要覆盖object.Finalize。相反,提供一个析构函数

时间:2009-08-26 06:18:46

标签: c# idisposable destructor finalizer

在以下代码中获取上述错误。如何纠正它。谢谢。 请找

protected override void Finalize() {     Dispose(false); } 

在下面的代码中。

using Microsoft.Win32; 
using System.Runtime.InteropServices; 

public class Kiosk : IDisposable 
{ 

    #region "IDisposable" 

    // Implementing IDisposable since it might be possible for 
    // someone to forget to cause the unhook to occur. I didn't really 
    // see any problems with this in testing, but since the SDK says 
    // you should do it, then here's a way to make sure it will happen. 

    public void Dispose() 
    { 
        Dispose(true); 
        GC.SuppressFinalize(this); 
    } 

    protected virtual void Dispose(bool disposing) 
    { 
        if (disposing) { 
        } 
        // Free other state (managed objects). 
        if (m_hookHandle != 0) { 
            UnhookWindowsHookEx(m_hookHandle); 
            m_hookHandle = 0; 
        } 
        if (m_taskManagerValue > -1) { 
            EnableTaskManager(); 
        } 
    } 

    protected override void Finalize() 
    { 
        Dispose(false); 
    } 

    #endregion 
} 

3 个答案:

答案 0 :(得分:11)

Finalize()是一种无法在代码中覆盖的特殊方法。请改用析构函数语法:

~Kiosk() 
{ 
    Dispose(false); 
} 

答案 1 :(得分:7)

做它说的话。而不是:

protected override void Finalize() 
{ 
    Dispose(false); 
} 

有:

~Kiosk () 
{ 
    Dispose(false); 
} 

答案 2 :(得分:1)

在C#中,以下语法完全符合您要完成的任务。

~Kiosk()
{
    Dispose(false);
}