改变数组大小

发布于 2024-10-15 02:46:25 字数 80 浏览 2 评论 0 原文

声明后是否可以更改数组大小? 如果没有,是否有数组的替代方案?
我不想创建一个大小为 1000 的数组,但在创建数组时我不知道数组的大小。

Is it possible to change an array size after declaration?
If not, is there any alternative to arrays?
I do not want to create an array with a size of 1000, but I do not know the size of the array when I'm creating it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

醉梦枕江山 2024-10-22 02:46:25

您可以使用 Array.Resize(),记录在 MSDN 中

但是,是的,我同意 Corey 的观点,如果您需要动态大小的数据结构,我们有 List

重要提示:Array.Resize() 不会调整数组大小(方法名称具有误导性),它会创建一个新数组并且仅替换您传递给该方法的引用

一个例子:

var array1 = new byte[10];
var array2 = array1;
Array.Resize<byte>(ref array1, 20);

// Now:
// array1.Length is 20
// array2.Length is 10
// Two different arrays.

You can use Array.Resize(), documented in MSDN.

But yeah, I agree with Corey, if you need a dynamically sized data structure, we have Lists for that.

Important: Array.Resize() doesn't resize the array (the method name is misleading), it creates a new array and only replaces the reference you passed to the method.

An example:

var array1 = new byte[10];
var array2 = array1;
Array.Resize<byte>(ref array1, 20);

// Now:
// array1.Length is 20
// array2.Length is 10
// Two different arrays.
晨曦÷微暖 2024-10-22 02:46:25

不,请尝试使用强类型列表

例如:

您可以这样做,而不是使用

int[] myArray = new int[2];
myArray[0] = 1;
myArray[1] = 2;

List<int> myList = new List<int>();
myList.Add(1);
myList.Add(2);

列表使用数组来存储数据,这样您就可以通过添加和删除项目而无需担心 LinkedList 的便利性,从而获得数组的速度优势。必须手动更改其大小。

但这并不意味着数组的大小(在本例中为 List)不会改变 - 因此强调手动这个词。

一旦数组达到预定义的大小,JIT 就会在堆上分配一个两倍大小的新数组,并复制现有数组。

No, try using a strongly typed List instead.

For example:

Instead of using

int[] myArray = new int[2];
myArray[0] = 1;
myArray[1] = 2;

You could do this:

List<int> myList = new List<int>();
myList.Add(1);
myList.Add(2);

Lists use arrays to store the data so you get the speed benefit of arrays with the convenience of a LinkedList by being able to add and remove items without worrying about having to manually change its size.

This doesn't mean an array's size (in this instance, a List) isn't changed though - hence the emphasis on the word manually.

As soon as your array hits its predefined size, the JIT will allocate a new array on the heap that is twice the size and copy your existing array across.

难得心□动 2024-10-22 02:46:25

是的,可以调整数组的大小。例如:

int[] arr = new int[5];
// increase size to 10
Array.Resize(ref arr, 10);
// decrease size to 3
Array.Resize(ref arr, 3);

如果使用 CreateInstance() 方法创建数组,则 Resize() 方法不起作用。例如:

// create an integer array with size of 5
var arr = Array.CreateInstance(typeof(int), 5);
// this not work
Array.Resize(ref arr, 10);

数组大小不是动态的,即使我们可以调整它的大小。如果你想要一个动态数组,我想我们可以使用通用List来代替。

var list = new List<int>();
// add any item to the list
list.Add(5);
list.Add(8);
list.Add(12);
// we can remove it easily as well
list.Remove(5);
foreach(var item in list)
{
  Console.WriteLine(item);
}

Yes, it is possible to resize an array. For example:

int[] arr = new int[5];
// increase size to 10
Array.Resize(ref arr, 10);
// decrease size to 3
Array.Resize(ref arr, 3);

If you create an array with CreateInstance() method, the Resize() method is not working. For example:

// create an integer array with size of 5
var arr = Array.CreateInstance(typeof(int), 5);
// this not work
Array.Resize(ref arr, 10);

The array size is not dynamic, even we can resize it. If you want a dynamic array, I think we can use generic List instead.

var list = new List<int>();
// add any item to the list
list.Add(5);
list.Add(8);
list.Add(12);
// we can remove it easily as well
list.Remove(5);
foreach(var item in list)
{
  Console.WriteLine(item);
}
掀纱窥君容 2024-10-22 02:46:25

您可以在 .net 3.5 及更高版本中使用 Array.Resize() 。该方法分配一个指定大小的新数组,将旧数组中的元素复制到新数组,然后用新数组替换旧数组。
(因此您将需要两个数组可用的内存,因为这可能在幕后使用 Array.Copy )

You can use Array.Resize() in .net 3.5 and higher. This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.
(So you will need the memory available for both arrays as this probably uses Array.Copy under the covers)

陌路黄昏 2024-10-22 02:46:25

在 C# 中,数组不能动态调整大小。

  • 一种方法是使用
    System.Collections.ArrayList
    原生数组

  • 另一个(更快)的解决方案是
    重新分配数组
    不同的尺寸并复制
    将旧数组的内容复制到新数组中
    数组。

    通用函数resizeArray(如下)可用于执行此操作。

    public static System.Array ResizeArray (System.Array oldArray, int newSize)  
        {
          int oldSize = oldArray.Length;
          System.Type elementType = oldArray.GetType().GetElementType();
          System.Array newArray = System.Array.CreateInstance(elementType,newSize);
    
          int keepLength = System.Math.Min(oldSize,newSize);
    
          如果(保留长度> 0)
          System.Array.Copy(oldArray,newArray,preserveLength);
    
         返回新数组; 
      }  
    
     公共静态无效主要()  
           {
            int[] a = {1,2,3};
            a = (int[])ResizeArray(a,5);
            a[3] = 4;
            a[4] = 5;
    
            for (int i=0; i

In C#, arrays cannot be resized dynamically.

  • One approach is to use
    System.Collections.ArrayList instead
    of a native array.

  • Another (faster) solution is to
    re-allocate the array with a
    different size and to copy the
    contents of the old array to the new
    array.

    The generic function resizeArray (below) can be used to do that.

    public static System.Array ResizeArray (System.Array oldArray, int newSize)  
        {
          int oldSize = oldArray.Length;
          System.Type elementType = oldArray.GetType().GetElementType();
          System.Array newArray = System.Array.CreateInstance(elementType,newSize);
    
          int preserveLength = System.Math.Min(oldSize,newSize);
    
          if (preserveLength > 0)
          System.Array.Copy (oldArray,newArray,preserveLength);
    
         return newArray; 
      }  
    
     public static void Main ()  
           {
            int[] a = {1,2,3};
            a = (int[])ResizeArray(a,5);
            a[3] = 4;
            a[4] = 5;
    
            for (int i=0; i<a.Length; i++)
                  System.Console.WriteLine (a[i]); 
            }
    
蝶舞 2024-10-22 02:46:25

请改用 List。 而不是整数数组

private int[] _myIntegers = new int[1000];

使用

private List<int> _myIntegers = new List<int>();

例如,稍后

_myIntegers.Add(1);

Use a List<T> instead. For instance, instead of an array of ints

private int[] _myIntegers = new int[1000];

use

private List<int> _myIntegers = new List<int>();

later

_myIntegers.Add(1);
若无相欠,怎会相见 2024-10-22 02:46:25

对于字节数组使用此方法:

最初:

byte[] bytes = new byte[0];

每当需要时(需要提供原始长度以进行扩展):

Array.Resize<byte>(ref bytes, bytes.Length + requiredSize);

重置:

Array.Resize<byte>(ref bytes, 0);

类型化列表方法

最初:

List<byte> bytes = new List<byte>();

每当需要时:

bytes.AddRange(new byte[length]);

释放/清除:

bytes.Clear()

Used this approach for array of bytes:

Initially:

byte[] bytes = new byte[0];

Whenever required (Need to provide original length for extending):

Array.Resize<byte>(ref bytes, bytes.Length + requiredSize);

Reset:

Array.Resize<byte>(ref bytes, 0);

Typed List Method

Initially:

List<byte> bytes = new List<byte>();

Whenever required:

bytes.AddRange(new byte[length]);

Release/Clear:

bytes.Clear()
匿名的好友 2024-10-22 02:46:25

在 C# 中,Array.Resize 是将任何数组大小调整为新大小的最简单方法,例如:

Array.Resize<LinkButton>(ref area, size);

这里,我想调整 LinkBut​​ton 数组的数组大小:

= 指定数组类型
ref area = ref 是关键字,'area' 是数组名称
size = 新的大小数组

In C#, Array.Resize is the simplest method to resize any array to new size, e.g.:

Array.Resize<LinkButton>(ref area, size);

Here, i want to resize the array size of LinkButton array:

<LinkButton> = specifies the array type
ref area = ref is a keyword and 'area' is the array name
size = new size array

街角迷惘 2024-10-22 02:46:25
    private void HandleResizeArray()
    {
        int[] aa = new int[2];
        aa[0] = 0;
        aa[1] = 1;

        aa = MyResizeArray(aa);
        aa = MyResizeArray(aa);
    }

    private int[] MyResizeArray(int[] aa)
    {
        Array.Resize(ref aa, aa.GetUpperBound(0) + 2);
        aa[aa.GetUpperBound(0)] = aa.GetUpperBound(0);
        return aa;
    }
    private void HandleResizeArray()
    {
        int[] aa = new int[2];
        aa[0] = 0;
        aa[1] = 1;

        aa = MyResizeArray(aa);
        aa = MyResizeArray(aa);
    }

    private int[] MyResizeArray(int[] aa)
    {
        Array.Resize(ref aa, aa.GetUpperBound(0) + 2);
        aa[aa.GetUpperBound(0)] = aa.GetUpperBound(0);
        return aa;
    }
独木成林 2024-10-22 02:46:25

如果您确实需要将其恢复为数组,我发现最简单的方法是将数组转换为列表,展开列表,然后将其转换回数组。

        string[] myArray = new string[1] {"Element One"};
        // Convert it to a list
        List<string> resizeList = myArray.ToList();
        // Add some elements
        resizeList.Add("Element Two");
        // Back to an array
        myArray = resizeList.ToArray();
        // myArray has grown to two elements.

If you really need to get it back into an array I find it easiest to convert the array to a list, expand the list then convert it back to an array.

        string[] myArray = new string[1] {"Element One"};
        // Convert it to a list
        List<string> resizeList = myArray.ToList();
        // Add some elements
        resizeList.Add("Element Two");
        // Back to an array
        myArray = resizeList.ToArray();
        // myArray has grown to two elements.
百思不得你姐 2024-10-22 02:46:25

当您想要添加/删除数据时,请使用列表(其中 T 是任何类型或对象),因为调整数组大小的成本很高。您可以阅读有关被认为有些有害的数组的更多信息 而列表可以添加到新记录可以追加到末尾。它根据需要调整其大小。

可以使用集合初始值设定项通过以下方式初始化列表

List<string> list1 = new List<string>()
{
    "carrot",
    "fox",
    "explorer"
};

将 var 关键字与集合初始值设定项一起使用。

var list2 = new List<string>()
{
    "carrot",
    "fox",
    "explorer"
};

使用新数组作为参数。

string[] array = { "carrot", "fox", "explorer" };
List<string> list3 = new List<string>(array);

在构造函数和赋值中使用容量。

List<string> list4 = new List<string>(3);
list4.Add(null); // Add empty references. (Not Recommended)
list4.Add(null);
list4.Add(null);
list4[0] = "carrot"; // Assign those references.
list4[1] = "fox";
list4[2] = "explorer";

对每个元素使用 Add 方法。

List<string> list5 = new List<string>();
list5.Add("carrot");
list5.Add("fox");
list5.Add("explorer");

因此,对于对象列表,您可以与列表初始化内联地分配和指定对象的属性。对象初始值设定项和集合初始值设定项共享相似的语法。

class Test
{
    public int A { get; set; }
    public string B { get; set; }
}

使用集合初始值设定项初始化列表。

List<Test> list1 = new List<Test>()
{
    new Test(){ A = 1, B = "Jessica"},
    new Test(){ A = 2, B = "Mandy"}
};

使用新对象初始化列表。

List<Test> list2 = new List<Test>();
list2.Add(new Test() { A = 3, B = "Sarah" });
list2.Add(new Test() { A = 4, B = "Melanie" });

Use a List (where T is any type or Object) when you want to add/remove data, since resizing arrays is expensive. You can read more about Arrays considered somewhat harmful whereas a List can be added to New records can be appended to the end. It adjusts its size as needed.

A List can be initalized in following ways

Using collection initializer.

List<string> list1 = new List<string>()
{
    "carrot",
    "fox",
    "explorer"
};

Using var keyword with collection initializer.

var list2 = new List<string>()
{
    "carrot",
    "fox",
    "explorer"
};

Using new array as parameter.

string[] array = { "carrot", "fox", "explorer" };
List<string> list3 = new List<string>(array);

Using capacity in constructor and assign.

List<string> list4 = new List<string>(3);
list4.Add(null); // Add empty references. (Not Recommended)
list4.Add(null);
list4.Add(null);
list4[0] = "carrot"; // Assign those references.
list4[1] = "fox";
list4[2] = "explorer";

Using Add method for each element.

List<string> list5 = new List<string>();
list5.Add("carrot");
list5.Add("fox");
list5.Add("explorer");

Thus for an Object List you can allocate and assign the properties of objects inline with the List initialization. Object initializers and collection initializers share similar syntax.

class Test
{
    public int A { get; set; }
    public string B { get; set; }
}

Initialize list with collection initializer.

List<Test> list1 = new List<Test>()
{
    new Test(){ A = 1, B = "Jessica"},
    new Test(){ A = 2, B = "Mandy"}
};

Initialize list with new objects.

List<Test> list2 = new List<Test>();
list2.Add(new Test() { A = 3, B = "Sarah" });
list2.Add(new Test() { A = 4, B = "Melanie" });
场罚期间 2024-10-22 02:46:25

这对我从类数组创建动态数组很有效。

var s = 0;
var songWriters = new SongWriterDetails[1];
foreach (var contributor in Contributors)
{
    Array.Resize(ref songWriters, s++);
    songWriters[s] = new SongWriterDetails();
    songWriters[s].DisplayName = contributor.Name;
    songWriters[s].PartyId = contributor.Id;
    s++;
}

This worked well for me to create a dynamic array from a class array.

var s = 0;
var songWriters = new SongWriterDetails[1];
foreach (var contributor in Contributors)
{
    Array.Resize(ref songWriters, s++);
    songWriters[s] = new SongWriterDetails();
    songWriters[s].DisplayName = contributor.Name;
    songWriters[s].PartyId = contributor.Id;
    s++;
}
不如归去 2024-10-22 02:46:25

使用通用列表 (System.Collections.Generic.List)。

Use a generic List (System.Collections.Generic.List).

新一帅帅 2024-10-22 02:46:25

如果您无法使用 Array.Reset(变量不是本地变量),则使用 Concat & ToArray 帮助:

anObject.anArray.Concat(new string[] { newArrayItem }).ToArray();

In case you cannot use Array.Reset (the variable is not local) then Concat & ToArray helps:

anObject.anArray.Concat(new string[] { newArrayItem }).ToArray();
み零 2024-10-22 02:46:25

我正在寻找一种使用 while 循环在简单的猜谜游戏中增加数组长度的方法。该数组的长度初始化为 1。我使用“i”(初始化为 0)来记录当前循环中的猜测次数。第 2 行显示数组中的最低分数。在增加下一轮的数组位置后,我使用 Array.Resize() 将数组的长度扩展了 i + 1。这样,数组长度随着循环的每次迭代而扩展。

arr[i] = guesses; 
Console.WriteLine("Best Score: {0}", arr.Min()); 
i++; 
Array.Resize(ref arr, i + 1); 

I was looking for a way to increment the length of my array in a simple guessing game using while loops. The array was initialised with a length of 1. I used 'i' (initialised at 0) to record the number of guesses in the current round of the loop. Line 2 displays the lowest score in the array. After incrementing the array position for the next round, I used Array.Resize() to extend the length of the array by i + 1. This way, the array length extends with each iteration of the loop.

arr[i] = guesses; 
Console.WriteLine("Best Score: {0}", arr.Min()); 
i++; 
Array.Resize(ref arr, i + 1); 
故事↓在人 2024-10-22 02:46:25
static void Resize(ref int[] Arr, int k)
{
    int[] newArray = new int[k];
    for (int i = 0; i < k; i++)
        newArray[i]=arr[i];            
    Arr=newArray;
}
static void Resize(ref int[] Arr, int k)
{
    int[] newArray = new int[k];
    for (int i = 0; i < k; i++)
        newArray[i]=arr[i];            
    Arr=newArray;
}
离旧人 2024-10-22 02:46:25

我将给出一个非常不同的答案。是的,你不需要列表或 Array.Resize!示例:

int[] arr = className.MethodName(arguments); \\ has size in ex. 10
arr = className.MethodName(newArguments); \\ now has a different size

您的类方法可以更新数组大小,没问题。在上面的代码中相应地替换类名和方法名以及参数。

I'm going to give a very different answer. Yes and you don't need lists or Array.Resize!! Example:

int[] arr = className.MethodName(arguments); \\ has size in ex. 10
arr = className.MethodName(newArguments); \\ now has a different size

your class methods can update the array size, no problem. In the code above replace the class name and method name and arguments accordingly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文