本文介绍了当父类也实现 IDisposable 时,在子类上实现 IDisposable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父类和子类,它们都需要实现 IDisposable.virtual(和base.Dispose()?)调用应该在哪里发挥作用?当我只是覆盖 Dispose(bool disposing) 调用时,我在没有显式的 Dispose() 函数的情况下实现了 IDisposable 感觉真的很奇怪(仅利用继承的),但拥有其他一切.

I have a parent and child class that both need to implement IDisposable. Where should virtual (and base.Dispose()?) calls come into play? When I just override the Dispose(bool disposing) call, it feels really strange stating that I implement IDisposable without having an explicit Dispose() function (just utilizing the inherited one), but having everything else.

我一直在做的事情(相当琐碎):

What I had been doing (trivialized quite a bit):

internal class FooBase : IDisposable
{
    Socket baseSocket;

    private void SendNormalShutdown() { }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private bool _disposed = false;
    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                SendNormalShutdown();
            }
            baseSocket.Close();
        }
    }

    ~FooBase()
    {
        Dispose(false);
    }
}

internal class Foo : FooBase, IDisposable
{
    Socket extraSocket;

    private bool _disposed = false;
    protected override void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            extraSocket.Close();
        }
        base.Dispose(disposing);
    }

    ~Foo()
    {
        Dispose(false);
    }

}

推荐答案

这是你不应该关心的事情.

This is something you shouldn't be concerned with.

当您对 IDisposable 类进行子类化时,基类已经为您处理了所有处理模式"管道.除了覆盖 protected Dispose(bool) 方法之外,您真的应该什么都不做,并跟踪您是否已经被处理(以正确引发 ObjectDisposedException.)

When you subclass an IDisposable class, all of the "Dispose pattern" plumbing is already being handled for you by the base class. You really should do nothing but override the protected Dispose(bool) method, and track whether you've been disposed already (to properly raise ObjectDisposedException.)

有关详细信息,请参阅我关于 从 IDisposable 类继承.

For details, see my blog post on Subclassing from an IDisposable class.

此外,通常考虑封装 IDisposable 类而不是子类化它是个好主意.有时对 IDisposable 类进行子类化是合适的,但这种情况很少见.封装通常是更好的选择.

Also, often, it's a good idea to consider encapsulating the IDisposable class instead of subclassing it. There are times when subclassing an IDisposable class is appropriate, but they are somewhat rare. Encapsulation is often a better alternative.

这篇关于当父类也实现 IDisposable 时,在子类上实现 IDisposable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:49