您是否需要处理对象并将其设置为null,或者当它们超出作用域时,垃圾收集器将清理它们?
当前回答
A little late to the party, but there is one scenario that I don't think has been mentioned here - if class A implements IDisposable, and exposes public properties that are also IDisposable objects, then I think it's good practice for class A not only to dispose of the disposable objects that it has created in its Dispose method, but also to set them to null. The reason for this is that disposing an object and letting it get GCed (because there are no more references to it) are by no means the same thing, although it is pretty definitely a bug if it happens. If a client of Class A does dispose its object of type ClassA, the object still exists. If the client then tries to access one of these public properties (which have also now been disposed) the results can be quite unexpected. If they have been nulled as well as disposed, there will be a null reference exception immediately, which will make the problem easier to diagnose.
其他回答
当对象不再被使用并且垃圾回收器认为合适时,对象将被清理。有时,您可能需要将一个对象设置为null以使其超出作用域(例如您不再需要其值的静态字段),但总体而言,通常不需要将其设置为null。
关于处置对象,我同意@Andre的观点。如果对象是IDisposable的,那么在不再需要它时释放它是个好主意,特别是当对象使用非托管资源时。不处理非托管资源将导致内存泄漏。
一旦程序离开using语句的作用域,就可以使用using语句自动处理对象。
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();
}
}
如果对象实现了IDisposable,那么是的,你应该释放它。对象可能挂在本地资源(文件句柄、操作系统对象)上,否则这些资源可能不会立即释放。这可能导致资源短缺、文件锁定问题和其他本来可以避免的微妙错误。
参见在MSDN上实现一个Dispose方法。
我也得回答。 JIT从对变量使用情况的静态分析中生成表和代码。 这些表项是当前堆栈帧中的“GC-Roots”。随着指令指针的前进,这些表项变得无效,因此准备进行垃圾收集。 因此:如果它是一个作用域变量,你不需要将它设置为null - GC将收集该对象。 如果它是一个成员或静态变量,则必须将其设置为null
如果它们实现了IDisposable接口,那么你应该释放它们。垃圾收集器会处理剩下的事情。
EDIT:处理一次性物品时最好使用using命令:
using(var con = new SqlConnection("..")){ ...
在c#中,你永远不需要将对象设置为空。编译器和运行时将负责找出它们何时不再在作用域中。
是的,你应该处理实现IDisposable的对象。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 为什么Visual Studio 2015/2017/2019测试运行器没有发现我的xUnit v2测试
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 没有ListBox。SelectionMode="None",是否有其他方法禁用列表框中的选择?
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何在iis7应用程序池中设置。net Framework 4.5版本