How should I inherit IDisposable?

前端 未结 6 1081
南笙
南笙 2021-02-04 01:31

Class names have been changed to protect the innocent.

If I have an interface named ISomeInterface. I also have classes that inherit the interface, FirstClass

6条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-04 02:11

    If you want all your code to deal with ISomeInterfaces generically, then yes they should all be disposable.

    If not, then the code that creates FirstClass should dispose it:

    using (FirstClass foo = new FirstClass()) {
        someObjectThatWantsISomeInterface.Act(foo);
    }
    

    otherwise, you could always use something like this extension method:

    public static void DisposeIfPossible(this object o) {
        IDisposable disp = o as IDisposable;
        if (disp != null)
            disp.Dispose();
    }
    
    // ...
    someObject.DisposeIfPossible(); // extension method on object
    

    I should also mention that I would prefer a template base class approach to this. I stubbed this out in this blog on building disposable things properly.

提交回复
热议问题