当摧毁一个物体? [英] When destroy an object?

查看:49
本文介绍了当摧毁一个物体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是问题。



关于垃圾收集的以下哪些陈述是错误的?



a。一般情况下,您无法确定GC何时执行垃圾收集。

b。程序可以在没有执行垃圾收集的情况下运行。

c。对象的Dispose方法可以调用GC.SuppressFinalize来阻止GC调用对象的析构函数。

d。在销毁一个对象之前,GC调用它的Dispose方法。

我认为答案是 d 但不确定。你会解释一下吗?

Here is the question.

Which of the following statements about garbage collection is false?

a. In general, you can’t tell when the GC will perform garbage collection.
b. It is possible for a program to run without ever performing garbage collection.
c. An object’s Dispose method can call GC.SuppressFinalize to prevent the GC from calling the object’s destructor.
d. Before destroying an object, the GC calls its Dispose method.
I think that the answer is d but not sure. Would you explain it?

推荐答案

好吧,想一想:

a)你能说出GC运行的时间吗?如果是这样,怎么样?

除非你强制GC运行,否则GC的整个想法是你无法分辨的。

b)一个程序可以运行吗? GC运行吗?你能写一个永远不需要GC的程序吗?

你当然可以!如果您的Main方法没有创建任何对象,并立即退出,那么从不需要GC,因为内存永远不会变低。

c)查看文档: MSDN [ ^ ]

它包括以下行:Dispose方法执行所有对象清理,所以垃圾收集器不再需要调用对象的Object.Finalize覆盖。因此,调用SuppressFinalize方法可以防止垃圾收集器运行终结器。

所以是的,你可以调用SuppressFinalize它会抑制析构函数调用,因为清理工作已经完成而且不需要重复。



所以留下D为假。

C的答案涵盖了原因。
Well, think about it:
a) Can you tell when the GC is running? If so, how?
The whole idea of a GC is that you can't tell, unless you force the GC to run.
b) Can a program run without the GC running at all? Can you write a program that would never need the GC?
Of course you can! If your Main method creates no objects, and exits immediately, then the GC is never needed because memory never becomes low.
c) Look at the documentation: MSDN[^]
It includes the line: "The Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object.Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer."
So yes, you can call SuppressFinalize and it will suppress the destructor call, because the clean-up is already done and does not need to be repeated.

So that leaves D as false.
And the Answer to C covers why.


这篇关于当摧毁一个物体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆