是否存在实现IDisposable类DisposableClass1的最佳实践,该类包含多个DisisableClass2类型的IDisposable字段,并且其中:
我写了一些代码来显示情况,但是对我来说看起来很丑。有办法改善吗?
public class DisposableClass1 : IDisposable
{
private List<DisposableClass2> DFields;
public DisposableClass1()
{
DFields = new List<DisposableClass2>();
try
{
for (var i = 0; i < 100; i++)
{
DFields.Add(new DisposableClass2());
}
}
catch (Exception)
{
Dispose(throwException: false);
throw;
}
}
public void Dispose()
{
Dispose(throwException: true);
}
private void Dispose(bool throwException)
{
var exceptions = new List<Exception>();
foreach (var f in DFields)
{
try
{
f.Dispose();
}
catch (Exception e)
{
exceptions.Add(e);
}
}
if (exceptions.Count > 0 && throwException)
throw new AggregateException(exceptions);
}
}
// We can't modify this class
public class DisposableClass2 : IDisposable
{
public DisposableClass2()
{
// May throw exception.
}
public void Dispose()
{
// May throw exception.
}
~DisposableClass2()
{
// May throw exception.
}
}