简体   繁体   English

如何在C#中向数组添加元素?

[英]How to add elements to an array in c#?

How can this method add items to an array in C# ? 此方法如何在C#中将项目添加到数组中?

class Set 
{
    int [] arr = {1,2,5,4};
    int [] arr2 = {3,2,4,8};

    public void AddElement()
    {
        arr.add(90);
    }
}

Arrays are fixed size. 数组是固定大小的。 If you want to add element to array, you need to create a new one, copy values and then store new value. 如果要向数组添加元素,则需要创建一个新元素,复制值,然后存储新值。

But in C# there is Collections, for instance List class (it's in System.Collections.Generic). 但是在C#中有Collections,例如List类(在System.Collections.Generic中)。

var list = new List<int>() { 1, 2, 3 };
list.Add(100);

There is solution for arrays. 有数组的解决方案。

class Set 
{
    int[] arr = { 1, 2, 5, 4 };
    int[] arr2 = { 3, 2, 4, 8 };

    public void AddElement() 
    {
        var newArray = new int[arr.Length + 1];
        Array.Copy(arr, newArray, arr.Length);
        newArray[newArray.Length - 1] = 90;
        arr = newArray;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM