我有一个接口的实现,该接口扩展了IDisposable
。在我的特定接口实现中,我不需要处理任何内容,所以我只是创建了一个空的Dispose()
方法。
public interface IMyStuff : IDisposable
{
}
public MyStuffImpl : IMyStuff
{
public void Dispose()
{
}
}
现在在FxCop中,这会导致CA1063警告:
Error, Certainty 95, for ImplementIDisposableCorrectly
{
Resolution : "Provide an overridable implementation of Dispose(
bool) on 'MyStuffImpl' or mark the type as sealed.
A call to Dispose(false) should only clean up native
resources. A call to Dispose(true) should clean up
both managed and native resources."
}
CriticalWarning, Certainty 75, for CallGCSuppressFinalizeCorrectly
{
Resolution : "Change 'MyStuffImpl.Dispose()' to call 'GC.SuppressFinalize(
object)'. This will prevent derived types that introduce
a finalizer from needing to re-implement 'IDisposable'
to call it."
}
Error, Certainty 95, for ImplementIDisposableCorrectly
{
Resolution : "Modify 'MyStuffImpl.Dispose()' so that it
calls Dispose(true), then calls GC.SuppressFinalize
on the current object instance ('this' or 'Me' in Visual
Basic), and then returns."
}
看起来我可以通过以下两种方式解决这个问题:
将该类设为sealed
:
public sealed MyStuffImpl : IMyStuff
{
public void Dispose()
{
}
}
实现典型模式的一部分:
public MyStuffImpl : IMyStuff
{
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
}
}
就我的情况而言,我并不打算扩展此实现,所以我可能会通过将其密封(sealed
)来解决问题,但我承认我不是很明白它是否被密封重要。
另外,仅仅因为我的类被密封了,FxCop不再告诉我Dispose()
应该调用GC.SupressFinalize(this);
,但这真的是事实吗?在.NET中无论何时都调用SupressFinalize
是更好的做法吗?
IEnumerator<T>
就是一个例子。 - phoogIDisposable
的东西,那么工厂的返回类型应该是IDisposable
。 这就是为什么IEnumerator<T>
实现IDisposable
的原因——它是一个工厂方法的返回类型。 - supercat