Who Disposes of an IDisposable public property?

前端 未结 10 1618
萌比男神i
萌比男神i 2020-12-03 09:59

If I have a SomeDisposableObject class which implements IDisposable:

class SomeDisposableObject : IDisposable
{
    public void Dis         


        
10条回答
  •  自闭症患者
    2020-12-03 10:27

    In general, I think whoever creates the object should be responsible for Disposal. In this case, AContainer creates SomeDisposableObject, so it should be Disposed when AContainer is.

    If, for some reason, you think that SomeDisposableObject should live longer than AContainer - I can only think of the following methods:

    • leave SomeDisposableObject unDisposed, in which case the GC will take care of it for you
    • give SomeDisposableObject a reference to AContainer (see WinForms Controls and Parent properties). As long as SomeDisposableObject is reachable, so is AContainer. That'll prevent the GC from Disposing AContainer, but if someone calls Dispose manually - well, you'd Dispose SomeDisposableObject. I'd say that's expected.
    • Implement SomeDisposableObject as a method, say CreateSomeDisposableObject(). That makes it clear(er) that the client is responsible for Disposal.

    All in all, though - I'm not really sure the design makes sense. After all, you seem to be expecting client code like:

    SomeDisposableObject d;
    using (var c = new AContainer()) {
       d = c.SomeObject;
    }
    // do something with d
    

    That seems like broken client code to me. It's violating Law of Demeter, and plain ol' common sense to me.

提交回复
热议问题