该方法如何将项目添加到C#中的数组?如何将元素添加到c#中的数组?
class Set
{
int [] arr = {1,2,5,4};
int [] arr2 = {3,2,4,8};
public void AddElement()
{
arr.add(90);
}
}
该方法如何将项目添加到C#中的数组?如何将元素添加到c#中的数组?
class Set
{
int [] arr = {1,2,5,4};
int [] arr2 = {3,2,4,8};
public void AddElement()
{
arr.add(90);
}
}
数组的大小是固定的。 如果要将元素添加到数组中,则需要创建一个新的元素,然后复制值并存储新值。
但在C#中有集合,例如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;
}
}
咦?您不要将方法添加到基元数据类型的数组中。请更具体一些。 – OldProgrammer
我的歉意!我试图创建一个标题为:public void AddElement(),该元素添加到任何一个数组的元素。 – Cb173
请解释[为什么你要这样做](http://meta.stackexchange.com/questions/66377/),因为你试图做的没有任何意义。 –