1
由於COM對象持有非內存資源但不支持IDisposable,因此我嘗試了一些想法來僞造它。你對我的第一次嘗試有什麼看法?IDisposable和COM
Public Function ComBlock(ByVal ParamArray comObjects As Object()) As IDisposable
For i As Integer = 0 To comObjects.Length - 1
If comObjects(i) Is Nothing Then Throw New ArgumentNullException("Null in parameter " & i)
If Not Marshal.IsComObject(comObjects(i)) Then Throw New ArgumentException(comObjects(i).GetType.Name & " is not a COM object")
Next
Return New ComContext(comObjects)
End Function
Private Class ComContext : Implements IDisposable
Private m_ComObjects As Object()
Private m_Disposed As Boolean
Sub New(ByVal comObjects As Object())
m_ComObjects = comObjects
End Sub
Private Sub Dispose() Implements IDisposable.Dispose
For Each item In m_ComObjects
Marshal.FinalReleaseComObject(item)
Next
GC.SuppressFinalize(Me)
End Sub
End Class
我會使用泛型而不是繼承的具體類型,但我看到你的觀點。 – 2010-02-26 21:58:14