问题描述
我能相信一个对象被销毁,其析构函数被立即调用,当它超出范围在C#?
Can I trust that an object is destroyed and its destructor is called immediately when it goes out of scope in C#?
我想,这应该因为许多常见的编码实践(如交易对象),依赖于这种行为,但我不是很习惯用垃圾收集工作,并没有什么见识到这种语言通常的行为。
I figure it should since many common coding practices (e.g. transaction objects) rely on this behaviour, but I'm not very used to working with garbage collection and have little insight to how such languages usually behave.
感谢。
推荐答案
不,.Net和hense C#依赖于一个垃圾回收的内存管理。所以析构函数(在.NET是所谓的终结)不会调用,直到GC发现它适当摧毁对象
Nope, .Net and hense C# relies on a garbage collection memory management. So destructors (which in .Net is called finalizers) are not called until GC finds it proper to destroy the objects.
此外:在C#中唐之最普通对象吨有析构函数。如果您需要析构函数的模式,你应该实现。一次性的对象,你也应该确保Dispose方法被调用,或者与 。或者直接调用方法
Additionally: most "regular" objects in C# don't have destructors. If you need the destructor pattern you should implement the IDisposable interface with the Dispose Pattern. On disposable objects you should also make sure that the Dispose method gets called, either with the using keyword or directly calling the method.
要进一步(希望)澄清:确定性处置净比如是非常有用的当你需要不是由.NET运行时管理明确地释放资源。这种资源的例子是文件句柄,数据库连接等,这通常是重要的,这些资源尽快,因为他们不再需要释放。因此,我们不能等待GC来释放他们。
To further (hopefully) clarify: deterministic disposal is useful in .Net e.g. when you need to explicitly free resources that is not managed by the .Net runtime. Examples of such resources are file handles, database connections, etc. It is usually important that these resources be freed as soon as they no longer are needed. Thus we cannot afford to wait for the GC to free them.
为了获得确定性处置的非确定性的世界(类似于C ++范围的行为)在净GC,.NET类依靠IDisposable接口上。从 Dispose模式,这里有一些例子:
In order to get deterministic disposal (similar to the scope behavior of C++) in the non-deterministic world of the .Net GC, the .Net classes rely on the IDisposable interface. Borrowing from the Dispose Pattern, here are some examples:
首先,实例化一个一次性的资源,然后让对象超出范围,会离开它的GC处置对象:
First, instantiating a disposable resource and then letting the object go out of scope, will leave it up to the GC to dispose the object:
1. {
2. var dr = new DisposableResource();
3. }
要解决这个问题,我们可以明确地处理对象:
To fix this we can explicitly dispose the object:
1. {
2. var dr = new DisposableResource();
3.
4. ...
5.
6. dr.Dispose();
7. }
但是,如果有什么不顺心的2号线和6之间错了吗?处置将不会被调用。为了进一步确保处置将最终被称为无论任何异常,我们可以做到以下几点:
But what if something goes wrong between line 2 and 6? Dispose will not be called. To further ensure that Dispose will finally be called regardless of any exceptions we can do the following:
1. var dr = new DisposableResource();
2. try
3. {
4. ...
5. }
6. finally
7. {
8. dr.Dispose();
9. }
由于这种模式通常需要,C#包括使用关键字来简化的东西。下面的例子是相当于上面:
Since this pattern is often needed, C# includes the using keyword to simplify things. The following example is equivalent to the above:
1. using (var dr = new DisposableResource())
2. {
3. ...
4. }
这篇关于C# - 走出去的范围时,对象立即销毁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!