我有一个或多或少像hastable一样工作的数组:基于索引,将在数组中放置一个值,因此该数组的某些索引将在其中包含值,而其他索引则可能会或不会。我有两段代码:
public void register( int index, string value )
{
_array[index] = value;
}
public void unregisterAll( )
{
/*
is this going to cause a memory leak when some of the values
are filled int the above function?
*/
_array = new string[12];
}
C#使用垃圾回收器。如果不再引用对象,则将在一段时间后自动将其释放。
当您执行此操作时(从垃圾收集器(GC)的角度来看) unregisterAll()
object_array`1: referenced by _array
// execute unregisterAll();
create object_array`2 and let _array reference it
// Some time later when the GC runs
object_array`1: not referenced
object_array`2: referenced by _array
// Some time later, when the GC decided to collect
collect object__array`1
请注意,这并不意味着您在C#中不会发生内存泄漏。一些对象使用非托管资源,这些资源需要手动处理(它们实现了IDisposable接口,您可以通过在using块中对它进行作用域化来自动处理该接口:
using(IDisposable disposable = new ...)
{
// use it
} // when leaving this scope disposable.Dispose() is automatically called
或者您可以通过调用Dispose()
它们来手动处理。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句