回答

1

这是准确的。如果Dispose(bool)方法完成了它的工作,那么再也没有任何意义让终结器再次执行它了。调用GC.SuppressFinalize()是一种优化,您可以停止.NET,因为它无法调用不执行任何操作的终结器。

我注意到你用大写字母C写了Class。这暗示你在VB.NET中编写你的代码。注意,IDE在99.99%的所有情况下都会执行错误的事情。只要你按输入“实现IDisposable”后回车键,插入错误代码:

Private disposedValue As Boolean = False  ' To detect redundant calls 

    ' IDisposable 
    Protected Overridable Sub Dispose(ByVal disposing As Boolean) 
     If Not Me.disposedValue Then 
      If disposing Then 
       ' TODO: free other state (managed objects). 
      End If 

      ' TODO: free your own state (unmanaged objects). 
      ' TODO: set large fields to null. 
     End If 
     Me.disposedValue = True 
    End Sub 

#Region " IDisposable Support " 
    ' This code added by Visual Basic to correctly implement the disposable pattern. 
    Public Sub Dispose() Implements IDisposable.Dispose 
     ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. 
     Dispose(True) 
     GC.SuppressFinalize(Me) 
    End Sub 
#End Region 

呸。这是一个终结器的样板实现,在MSDN Library btw中有详细记录。这是不对的。实际上需要一个终结器是非常罕见的,.NET类已经自己处理它。如果你真的使用操作系统句柄,那么你应该使用其中一个SafeHandle派生类。或者写你自己的包装。

编辑回本:

Public Sub Dispose() Implements IDisposable.Dispose 
    someField.Dispose() 
    '' maybe some more 
    ''... 
End Sub 
相关问题