Dot-Net

如何處置一次性物品清單?

  • July 16, 2020

我正在為一個類實現 IDisposable ,並且在處理時有一個一次性對象的內部列表。我是否應該通過循環處理這些對象。

public Class MyDisposable 
    Implements IDisposable 
    private _disposbaleObjects as new List(of OtherDisposables)

    Public Overloads Sub Dispose() Implements System.IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
   End Sub

   Protected Overridable Sub Dispose(ByVal disposing As Boolean)
       If Not Me.disposedValue Then
           If disposing Then
                 ? Should I dispose the the list like this ?
                 For Each obj In _disposbaleObjects
                     obj.dispose()
                 Next 
           End If               
       End If
       Me.disposedValue = True
   End Sub

End Class

是的,遍歷列表並處理每個項目。

您還可以編寫擴展方法:

public static void Dispose(this IEnumerable<IDisposable> collection)
{
   foreach (IDisposable item in collection)
   {
       if (item != null)
       {
           try
           {
               item.Dispose();
           }
           catch (Exception)
           {
               // log exception and continue
           }
       }
   }
}

並稱它為你的清單

coll.Dispose()

一次性集合,實現的集合IDisposable

public sealed class DisposableCollection<T> : Collection<T>, IDisposable
   where T : IDisposable
{
   public DisposableCollection(IList<T> items)
       : base(items)
   {
   }

   public void Dispose()
   {
       foreach (var item in this)
       {
           try
           {
               item.Dispose();
           }
           catch
           {
               // swallow
           }
       }
   }
}

用法:

using (var coll = new DisposableCollection(items))
{
    // use
}
// it has been disposed

引用自:https://stackoverflow.com/questions/3276495