有没有办法在对象被销毁时运行一些代码?
在 C# 中,我知道我的对象在超出范围时会被垃圾回收,并且不再有指向它的指针/引用。当垃圾收集发生时,有没有办法运行一些自定义代码?
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 custom code when this garbage collection occurs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,它称为终结器。终结器。 http://msdn.microsoft.com/en-us/library/wxad3cah.aspx
许多 C# 文档都混淆地使用了术语“析构函数”。尽管析构函数的 C++ 命名在 C# 中用于终结器,但语义完全不同。如果您始终使用“终结器”这个词,就不会有任何混淆。
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:
您可以使用
Finalizer/Destructor
(~
) 方法。MSDN - Object.Finalize
You can use the
Finalizer/Destructor
(~
) method.MSDN - Object.Finalize
C# 中没有相当于析构函数的东西 - 您能做的最好的事情就是添加 终结器(具有析构函数语法),然后安排在 GC 正常收集对象时在专用终结器线程上执行 - 这确实会导致额外的开销保持您的对象实例的存活时间比应有的时间长。仔细考虑用例。
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.