在C#中销毁变量或数组

Ale*_*xry 12 c# variables destructor

我有一个变量或数组,我不再需要它.如何摧毁他们?抱歉没有问题.

Dea*_*ing 11

你没有.只是让引用超出范围,它将自动被垃圾收集.


Pop*_*lin 5

在.Net或任何垃圾收集语言中,您只需释放您对该对象持有的所有引用,垃圾收集器最终将收集它Ex:

   int[] arr = new int[20];
   ....
   // when no longer needed set all references to null
   arr = null;
   // also creating a new object will release the old one automatically if there are no more references to it
   arr = new int[40]; // old array will be garbage collected
Run Code Online (Sandbox Code Playgroud)

另请注意,每次都不需要这样做,只有当您明确要释放对象而不释放它的父对象或者引用是静态字段时才需要这样做.对于本地(方法)变量,类或静态字段的字段也不需要释放对象.

  • 请注意,您也不需要将引用设置为"null" - JIT/Runtime将密谋确定代码将不再使用该引用的位置; 那时它已经死了,可收藏.谷歌在MSDN博客上的"GC.KeepAlive()"描述和SO的详细信息. (2认同)

Pie*_*rOz 2

在 .NET 中,垃圾收集器会为你做这件事!但实际上,这可能取决于您写下不再“需要”变量时的意思