Is there a way to run some code as an object is being destroyed?
In C# I know that my objects are garbage collected when they go out of scope and there are no more pointers/references to it. Is there a way to run some开发者_StackOverflow中文版 custom code when this garbage collection occurs?
Yes, it's called a finalizer. http://msdn.microsoft.com/en-us/library/wxad3cah.aspx
Much of the C# documentation confusingly uses the term "destructor". Although the C++ naming for a destructor is used in C# for a finalizer, the semantics are totally different. If you consistently use the word finalizer, there won't be any confusion.
Yes. You can define a finalizer for your class:
class Lava
{
~Lava() // Finalizer -- runs when object is collected
{
// TODO: Clean up molten rock
}
}
You can use the Finalizer/Destructor
(~
) method.
MSDN - Object.Finalize
There is no equivalent of a destructor in C# - the best you can do is add a finalizer (which has destructor syntax) which is then scheduled for execution on a dedicated finalizer thread when the GC would have normally collected your object - this does cause additional overhead though and keeps your object instance alive longer than it should have been. Consider the use case carefully.
精彩评论