通过将新值[]分配给填充数组,是否会导致内存泄漏

Gee*_*eek 2 c# arrays memory-leaks

我有一个或多或少像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];
}
Run Code Online (Sandbox Code Playgroud)

Roy*_* T. 7

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
Run Code Online (Sandbox Code Playgroud)

请注意,这并不意味着您不能在C#中发生内存泄漏.某些对象使用需要手动处理的非托管资源(它们实现了接口IDisposable,您可以通过在using块中对其进行范围设置来自动处理:

using(IDisposable disposable = new ...)
{
    // use it
} // when leaving this scope disposable.Dispose() is automatically called
Run Code Online (Sandbox Code Playgroud)

或者您可以通过调用Dispose()它们手动处理.