Using an object in a constructor which has to be Disposed of
In a class I am writing, I am using an object to set some of its properties in a custom class I am writing.
This is being done in the constructor, but the class ha开发者_如何学Pythons a Dispose() method.
I have never actually used an object in a constructor which has a Dispose() method/implements IDisposable. Should I wrap this in a using(...) statement or should I implement a destructor/finalizer?
My imagination has made me ask this: This class is part of a third party closed source API. How can I find out what needs to be disposed of?
Thanks
If your reference to the object is local to the constructor then just wrap it in a using statement.
If your reference to the object is a class member then your class should implement IDisposable as well, with it's Dispose() method calling Dispose() on the object.
Just to add in response to the other parts of your question:
- You should generally only implement a finalizer where you are using unmanaged resources which might need to be cleaned up if your program terminates abnormally. Any managed objects will be tidied up by the GC at some point. Don't rely on a finalizer to dispose of any managed objects as you can't predict when it will be executed.
- You don't need to care about what needs to be disposed of. You should trust that where a class implements IDisposable, it takes care of everything through that pattern. If it's badly coded then you may encounter problems, but I'd be optimistic in this case.
I'd always opt for wrapping IDisposables in a Using block where possible as I think it's neater than trying to call the Dispose() method explicitly.
if you don't need the object outside the constructor, why don't you use the using statement ? If there is a special "destruction" code - using is not enough and you need to call it's disposal code from some place...
精彩评论