你需要配置的对象,并将它们设置为null? [英] Do you need to dispose of objects and set them to null?

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

问题描述

您是否需要处置的对象,并将它们设置为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?

推荐答案

对象将被清理时不再使用他们和垃圾收集器认为合适的时候。有时,你可能需要一个对象,以使走出去的范围设置为(如静态字段,其值不再需要的),但总体通常没有必要设置为

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.

您可以使用使用语句来自动配置的对象,一旦程序离开使用语句的范围

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

哪个是功能上等同于:

Which is functionally equivalent to:

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

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

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