簡體   English   中英

如何在C#中向數組添加元素?

[英]How to add elements 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);
    }
}

數組是固定大小的。 如果要向數組添加元素,則需要創建一個新元素,復制值,然后存儲新值。

但是在C#中有Collections,例如List類(在System.Collections.Generic中)。

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

有數組的解決方案。

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