如何在c#中删除一个数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/584017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:12:44  来源:igfitidea点击:

How to delete an array in c#?

c#arrays

提问by Patrik Bj?rklund

I'm sorry if this is an obvious question but neither Google or a search here led me to an answer.

如果这是一个明显的问题,我很抱歉,但谷歌或这里的搜索都没有让我找到答案。

Is there a way to remove an array entirely?

有没有办法完全删除数组?

I want the oppositeof int[] array = new int[5]

我想要相反int[] array = new int[5]

采纳答案by RossFabricant

Say you call:

说你打电话:

 void Foo(){
     int[] a = new int[5];
 }

In C# there is no way to undefine the variable a. That means awill be defined in Fooeven if you set ato null. However, at the end of Fooawill fall out of scope. That means no code can reference it, and the garbage collector will take care of freeing the memory for you the next time it runs, which might not be for a long time.

在 C# 中,无法取消定义变量a。这意味着即使您设置为 nulla也会被定义。但是,最后将超出范围。这意味着没有代码可以引用它,垃圾收集器将在下次运行时为您释放内存,这可能不会持续很长时间。FooaFooa

回答by Marc Gravell

You just have to let it go out of scope, and wait for GC to find it; which might not be immediately (in fact, it almost certainly won't be). If you have a field on a long-lived object (that is going to stay in scope), then you can set to null, which can help.

你只需要让它超出范围,然后等待 GC 找到它;这可能不会立即发生(事实上,几乎肯定不会)。如果您在长期存在的对象上有一个字段(将保留在范围内),那么您可以设置为 null,这会有所帮助。

You can influence the GC to collect sooner (not just your object: everything eligible), but you should rarely if everdo this. I use it only in test rigs; but:

您可以影响GC收集越早(不只是你的对象:一切符合条件的),但你应该很少,如果以往任何时候都做到这一点。我只在测试台上使用它;但:

GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); // DON'T DO THIS!!!

for more on GC.Collect:

有关更多信息GC.Collect

回答by ShuggyCoUk

There is no need to delete the array, the GC will deal with it.

不需要删除数组,GC会处理。

(Very) Simplistically:

(非常)简单地说:

When you run out of memory the garbage collector will kick in, stop your code and traverse all the live objects in memory.
live means some reference on the stack, a register, a static reference and some other things known collectively as 'GC Roots'. As it traverses them it notes that they are alive.

当内存不足时,垃圾收集器将启动,停止您的代码并遍历内存中的所有活动对象。
live 意味着堆栈上的一些引用、寄存器、静态引用和其他一些统称为“GC 根”的东西。当它穿过它们时,它注意到它们还活着。

If your array is no longer live there is no way anything could access it anymore (that's what determines liveness) so the memory it occupied will be available for reuse.

如果您的数组不再存在,则任何东西都无法再访问它(这决定了活跃性),因此它占用的内存将可用于重用。

There maybe a reason to assign the reference to null if it would hold references alive longer than is desired or it is holding a large chunk of memory that you need immediately but this can easily backfire and actually make the array live longer. Instance rather than stack variables are better candidates for this optimisation if the containing instance will have considerably longer life than the array it contains.

可能是参考分配到空是否会持有引用比期望活得更长的一个原因,或者是抱着一大块的内存,你马上需要,但这样很容易适得其反,实际上使该数组长寿。如果包含实例的生命周期比它包含的数组长得多,那么实例变量而不是堆栈变量更适合进行此优化。

To be clear, as a beginner you should not be considering this sort of thing, let the GC do it's job and only try to help it when you:

需要明确的是,作为初学者,您不应该考虑这种事情,让 GC 完成它的工作,并且只有在您:

  1. know you need to
  2. know how to
  3. know how to check you did it right
  1. 知道你需要
  2. 知道怎么
  3. 知道如何检查你做对了

回答by Trap

array = null, but I think it'll be a good idea if you read a little about the .NET memory management model to fully understand why.

array = null,但我认为如果您阅读一些有关 .NET 内存管理模型的内容以完全理解原因,这将是一个好主意。

回答by Arjan Einbu

The closest you get is just to wait for it getting out of scope or setting it to null.

您得到的最接近的方法就是等待它超出范围或将其设置为 null。

It won't remove or delete the array immediately, but after you drop all references to the array, the garbage collector (GC) will delete it in time...

它不会立即移除或删除数组,但是在您删除对数组的所有引用后,垃圾收集器(GC)会及时删除它...

回答by mandaleeka

Just to clarify in case you don't understand some of the terminology expressed in the other answers, GC stands for garbage collector. Languages like C# that have automatic memory management allow you to focus on doing what needs to be done and not worry about what you're creating and when to delete it. The GC works by periodically going through all of the objects you create and seeing whether they have any references to them. If not, this means there's no way you can do anything with them, so they might as well be deleted, and the system does just that.

为了澄清以防万一您不理解其他答案中表达的某些术语,GC 代表垃圾收集器。像 C# 这样具有自动内存管理功能的语言使您可以专注于做需要做的事情,而不必担心您正在创建什么以及何时删除它。GC 的工作原理是定期检查您创建的所有对象并查看它们是否有任何对它们的引用。如果没有,这意味着您无法对它们做任何事情,因此不妨将它们删除,而系统会这样做。

For more details, see http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)

有关更多详细信息,请参阅http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)

回答by Greg Beech

You should read Chris Brumme's article on the subject; the first few paragraphs should explain the situation.

您应该阅读Chris Brumme 关于该主题的文章;前几段应说明情况。

And anybody suggesting "assign null to the variable" should take particular note of the part that says:

任何建议“为变量分配 null”的人都应该特别注意以下部分:

Even if you add “aC = null;” after your usage of it, the JIT is free to consider this assignment to be dead code and eliminate it.

即使你加上“aC = null;” 在您使用它之后,JIT 可以自由地将此分配视为死代码并消除它。

回答by DWolf

This may have been solved but you could treat the array like a stack. Loop through it and pop the top off each iteration.

这可能已经解决了,但您可以将数组视为堆栈。循环遍历它并在每次迭代中弹出顶部。

while(true)
{
    if(array.Length==0)
    {
        break;
    }
    array.Pop();
}

this way you can just push more values into the array without having to re-instantiate it

这样你就可以将更多的值推入数组而无需重新实例化它

回答by DWolf

You can declare and initialize your array in a if (true) {} statement, out of the if statement (after it) the array variable is not accessible, so it will be deleted then.

您可以在 if (true) {} 语句中声明和初始化数组,在 if 语句之外(在它之后),数组变量不可访问,因此它将被删除。

回答by Michieal

In C++ one can use the deletekeyword. And it was originally mentioned in this comment and in other comments. The edit history shows this. This is a viable (albeit side answer) even if others do not understand why. I say this because one can use it to find their own elegant solution, if they understand more than one language.

在 C++ 中,可以使用delete关键字。它最初是在此评论和其他评论中提到的。编辑历史显示了这一点。即使其他人不明白为什么,这也是一个可行的(尽管是侧面的答案)。我这样说是因为如果他们了解一种以上的语言,则可以使用它来找到自己的优雅解决方案。

In .NET/MSIL, you have the delete keyword, but it's called variablename.Dispose(). I'm offering this because it removes all references to the variable, and pushes it into a state of readiness for the garbage collection. Another option is to set the variable equal to nullas that will keep the variable as a typed object, but release what it held to the garbage collection, so that it can be reassigned later.

在 .NET/MSIL 中,您有 delete 关键字,但它称为variablename.Dispose()。我提供这个是因为它删除了对变量的所有引用,并将其推送到垃圾收集准备就绪的状态。另一种选择是将变量设置为null ,因为这会将变量保留为类型化对象,但将其持有的内容释放给垃圾收集器,以便以后可以重新分配。

Original Comment/Answer:

原始评论/答案:

The garbage collection for C# is great and all, but sometimes you really need to remove a variable from memory and make a new instance of it, without some other part of your program keeping it alive. One has the ability to potentially place the existing chunk of memory held by the array into a GC state, by pointing the array at a new piece of memory, such as:

C# 的垃圾收集非常棒,但有时您确实需要从内存中删除一个变量并为其创建一个新实例,而您的程序的其他部分却没有让它保持活动状态。通过将数组指向一块新内存,可以将数组持有的现有内存块潜在地置于 GC 状态,例如:

aMyArray = new int[];

The main problem that I can see with this way, however, is that you really do not want to waste a ton of memory, and then have everything come to a screeching halt as GC is started because the OS is freaking. I hold this thought, considering that C Sharp is now a mainstream language and is used in a LOT of different applications, including writing games... It'd truly be nice if C Sharp didn't act similar to ActionScript/FLASH in this respect.

但是,我可以通过这种方式看到的主要问题是,您真的不想浪费大量内存,然后在 GC 启动时突然停止一切,因为操作系统太糟糕了。我有这个想法,考虑到 C Sharp 现在是一种主流语言,并且被用于很多不同的应用程序,包括编写游戏......如果 C Sharp 在这方面没有类似于 ActionScript/FLASH 的行为真的很好尊重。