如何在 Visual C# 中清除数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1807307/
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-06 21:01:44  来源:igfitidea点击:

How to clear an array in Visual C#

c#arrays

提问by neuromancer

I have an array of ints. They start out with 0, then they get filled with some values. Then I want to set all the values back to 0 so that I can use it again, or else just delete the whole array so that I can redeclare it and start with an array of all 0s.

我有一个整数数组。它们从 0 开始,然后填充一些值。然后我想将所有值设置回 0 以便我可以再次使用它,或者只是删除整个数组以便我可以重新声明它并从一个全 0 的数组开始。

采纳答案by Jon Skeet

You can call Array.Clear:

您可以调用Array.Clear

int[] x = new int[10];
for (int i = 0; i < 10; i++)
{
    x[i] = 5;
}
Array.Clear(x, 0, x.Length);

Alternatively, depending on the situation, you may find it clearer to just create a new array instead. In particular, you then don't need to worry about whether some other code still has a reference to the array and expects the old values to be there.

或者,根据情况,您可能会发现只创建一个新数组更清晰。尤其是,您无需担心其他一些代码是否仍然具有对该数组的引用并期望旧值在那里。

I can't recall ever calling Array.Clearin my own code - it's just not something I've needed.

我不记得曾经调用Array.Clear过我自己的代码 - 这不是我需要的东西。

(Of course, if you're about to replace all the values anyway, you can do that without clearing the array first.)

(当然,如果您无论如何都要替换所有值,您可以在不先清除数组的情况下执行此操作。)