就像在 PHP 和其他一些语言中一样,有没有办法在不指定索引的情况下向数组添加值?
int[] aWhich = {};
aWhich[] = 1;
谢谢。
不适用于 anArray
或任何其他类型,因为索引器运算符必须具有至少一个参数(通过它不必是int
)。
但是,您可以添加到 a 的末尾List
:
List<int> aWhich = new List<int>();
aWhich.Add(1);
首先,您必须指定数组可以容纳的最大值数:
int[] MyArray = new int[14];
这里 14 是MyArray可以容纳的最大值数。
int value = 0;
void MyFuntion(){
MyArray[value] = 1;
value++;
}
通过这种方式,您可以在不指定索引号的情况下添加值,它将自动放置索引。
你不能。C#(和 .NET)中的数组是不可变的(就它们的大小而言,不一定是它们的内容),您可以通过索引访问它们的值。您正在寻找的是List、ArrayList或System.Collections或System.Collections.Generic命名空间中可能更适合您需要的东西。
还有另一种方法,Fist 将元素添加到 List,然后将其转换为数组。
例如:
var intList = new List<int>();
intList.Add(1);
intList.Add(2);
var intArray = intList.ToArray();
编辑:此方法不适用于添加新数组项。
myArray[myArray.Length] = newArrayItem;
.Length - #
将用于覆盖数组项。