假设我有一个类似如下的课程:
public class DisposableClass : IDisposable()
{
private readonly Timer timer;
DisposableClass()
{
this.timer = new Timer(s => cb(s), s, 1000, 1000);
}
Init()
{
try
{
// Do some initialization here that is not done in ctor.
}
catch (Exception)
{
// Log error.
throw;
}
finally
{
// Is this correct?
this.Dispose();
}
}
public void Dispose()
{
this.timer?.Dispose();
}
}
我的问题是,在抛出未处理异常时,对于任何非构造方法,上述情况下的finally
子句是否必要(或根本不需要)。谢谢。
编辑:
在回答中,请根据Init()
,public
,protected
可见度级别private
来解决问题。