using System;class Test
{
    Test()
    {
        Console.WriteLine("Test的构造数");
    }
    ~Test()
    {
        Console.WriteLine("Test的析构函数");
    }    void PrintAMessage(string msg)
    {
        Console.WriteLine("PrintAMessage:{0}", msg);
    }
    void Dispose()
    {
        Finalize();
        GC.SuppressFinalize(this);
    }    static void Main()
    {    }
}为什么在调用Finalize();方法时,会出错,
Finalize();方法不是在System名字空间下的Object类中嘛!
为什么不可以直接调用,还需要using别的名字空间吗?

解决方案 »

  1.   

    析构函数是执行清理操作的 C# 机制。析构函数提供了适当的保护措施,如自动调用基类型的析构函数。在 C# 代码中,不能调用或重写 Object.Finalize。Finalize 方法在未能调用 Dispose 方法的情况下充当防护措施来清理资源。您应该只实现 Finalize 方法来清理非托管资源。您不应该对托管对象实现 Finalize 方法,因为垃圾回收器会自动清理托管资源。默认情况下,Object.Finalize 方法不进行任何操作。如果要让垃圾回收器在回收对象的内存之前对对象执行清理操作,您必须在类中重写此方法。注意 
    您无法在 C# 或 C++ 编程语言中重写 Finalize 方法。在 C# 中可使用析构函数语法实现 Finalize 方法。在 .NET Framework 2.0 版中,C++ 为实现 Finalize 方法提供了自己的语法,如 Destructors and Finalizers in Visual C++ 中所述。在早期版本中,C++ 与 C# 一样也使用析构函数语法来实现 Finalize 方法。
     
    如果需要实现dispose 应该如下 首先继承IDispose接口  
    // Design pattern for a base class.
    public class Base: IDisposable
    {
       //Implement IDisposable.
       public void Dispose() 
       {
         Dispose(true);
          GC.SuppressFinalize(this); 
       }   protected virtual void Dispose(bool disposing) 
       {
          if (disposing) 
          {
             // Free other state (managed objects).
          }
          // Free your own state (unmanaged objects).
          // Set large fields to null.
       }   // Use C# destructor syntax for finalization code.
       ~Base()
       {
          // Simply call Dispose(false).
          Dispose (false);
       }
    }
    // Design pattern for a derived class.
    public class Derived: Base
    {   
       protected override void Dispose(bool disposing) 
       {
          if (disposing) 
          {
             // Release managed resources.
          }
          // Release unmanaged resources.
          // Set large fields to null.
          // Call Dispose on your base class.
          base.Dispose(disposing);
       }
       // The derived class does not have a Finalize method
       // or a Dispose method without parameters because it inherits
       // them from the base class.
    }