本文介绍了终结者有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在.NET中编程四年了(主要是C#),并且广泛使用了IDiposable,但是我还没有找到终结器的需要。终结器是干什么的?

I have been programming in .NET for four years (mostly C#) and I use IDiposable extensively, but I am yet to find a need for a finaliser. What are finalisers for?

推荐答案

终结器是最后的尝试,以确保正确清理某些东西,并且通常将其保留对于包装非托管资源的对象,例如将不会收集垃圾的非托管句柄等。

A finalizer is a last ditch attempt to ensure that something is cleaned up correctly, and is usually reserved for objects that wrap unmanaged resources, such as unmanaged handles etc that won't get garbage collected.

确实很少写终结器。幸运的是(与 IDisposable 不同),终结器不需要传播;因此,如果您有一个带有终结器的 ClassA 和一个包装 ClassA 的 ClassB code>,然后 ClassB 不需要终结器-但很有可能 ClassA ClassB 将实现 IDisposable

It is rare indeed to write a finalizer. Fortunately (and unlike IDisposable), finalizers don't need to be propagated; so if you have a ClassA with a finalizer, and a ClassB which wraps ClassA, then ClassB does not need a finalizer - but quite likely both ClassA and ClassB would implement IDisposable.

对于托管代码, IDisposable 通常就足够了。即使您没有正确清理,最终还是会收集托管对象(假设它们已释放)。

For managed code, IDisposable is usually sufficient. Even if you don't clean up correctly, eventually the managed objects will get collected (assuming they are released).

这篇关于终结者有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 07:09