您是否需要处理对象并将它们设置为空? [英] Do you need to dispose of objects and set them to null?

查看:30
本文介绍了您是否需要处理对象并将它们设置为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您是否需要处理对象并将它们设置为 null,或者当它们超出范围时垃圾收集器会清除它们?

Do you need to dispose of objects and set them to null, or will the garbage collector clean them up when they go out of scope?

推荐答案

当对象不再被使用并且垃圾收集器认为合适时,它们将被清理.有时,您可能需要将对象设置为 null 以使其超出范围(例如不再需要其值的静态字段),但总的来说通常不需要设置到 null.

Objects will be cleaned up when they are no longer being used and when the garbage collector sees fit. Sometimes, you may need to set an object to null in order to make it go out of scope (such as a static field whose value you no longer need), but overall there is usually no need to set to null.

关于处置对象,我同意@Andre.如果对象是IDisposable,那么当您不再需要它时处理它是个好主意,尤其是当对象使用非托管资源时.不处理非托管资源将导致内存泄漏.

Regarding disposing objects, I agree with @Andre. If the object is IDisposable it is a good idea to dispose it when you no longer need it, especially if the object uses unmanaged resources. Not disposing unmanaged resources will lead to memory leaks.

一旦您的程序离开using 语句的范围,您可以使用using 语句自动处理一个对象.

You can use the using statement to automatically dispose an object once your program leaves the scope of the using statement.

using (MyIDisposableObject obj = new MyIDisposableObject())
{
    // use the object here
} // the object is disposed here

在功能上等同于:

MyIDisposableObject obj;
try
{
    obj = new MyIDisposableObject();
}
finally
{
    if (obj != null)
    {
        ((IDisposable)obj).Dispose();
    }
}

这篇关于您是否需要处理对象并将它们设置为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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