当你的实现是一个空方法时,你如何“正确”实现Dispose()(根据FxCop)? (CA1063)

时间:2012-01-20 21:22:04

标签: c# .net idisposable fxcop

我有一个接口的实现,该接口扩展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?

2 个答案:

答案 0 :(得分:11)

除非您的实例有终结器,否则

SuppressFinalize()毫无意义 如果您的班级没有终结器,但不是sealed,那么您仍应SuppressFinalize,以防继承的班级添加终结器。

除了Dispose(bool)需要protected virtual之外,您的两个选项都是正确的。

答案 1 :(得分:2)

在“实施典型模式的一部分”选项中,您应该使用Dispose(bool)方法protected virtual

protected virtual void Dispose(bool disposing) 
{ 
} 

这将为子类提供处理其管理的任何资源的机会。这就是“提供一个可覆盖的Dispose(bool)实现”中“overridable”的含义

当然,public virtual也会满足FxCop。

相关问题