【发布时间】:2012-02-15 09:47:54
【问题描述】:
我有一个接口的实现,该接口扩展了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 中总是在 Dispose 中调用 SupressFinalize 是否“更好”?
【问题讨论】:
-
如果你的接口实现了不需要处理的接口,也许你的接口不应该实现 IDisposable。您还可以根据需要在界面中实现 IDisposable 。
-
@DBM OP 正在实现另一个继承 IDisposable 的接口。
IEnumerator<T>就是一个例子。 -
@DBM:如果大多数实现都是一次性的,那么这个接口也应该是一次性的,以鼓励该接口的用户正确处理。
-
我不知道 FxCop 在做什么,但我想指出您的课程实际上缺少终结器。所以 SuppressFinalize 什么都不做。
-
@DBM:如果工厂要返回的东西可能是
IDisposable,也可能不是,那么工厂的返回类型应该是IDisposable。这就是IEnumerator<T>实现IDisposable的原因——它是工厂方法的返回类型。
标签: c# .net idisposable fxcop