我有一个或多或少像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];
}
答案 0 :(得分:7)
C#使用垃圾收集器。如果某个对象不再被引用,那么(在一段时间后)会自动释放。
执行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(IDisposable disposable = new ...)
{
// use it
} // when leaving this scope disposable.Dispose() is automatically called
或者您可以通过调用Dispose()
手动处理它们。