可能是一个非常简单的一个-我开始用c#和需要添加值到一个数组,例如:

int[] terms;

for(int runs = 0; runs < 400; runs++)
{
    terms[] = runs;
}

对于那些使用过PHP的人,下面是我试图在c#中做的事情:

$arr = array();
for ($i = 0; $i < 10; $i++) {
    $arr[] = $i;
}

当前回答

你必须先分配数组:

int [] terms = new int[400]; // allocate an array of 400 ints
for(int runs = 0; runs < terms.Length; runs++) // Use Length property rather than the 400 magic number again
{
    terms[runs] = value;
}

其他回答

int[] terms = new int[10]; //create 10 empty index in array terms

//fill value = 400 for every index (run) in the array
//terms.Length is the total length of the array, it is equal to 10 in this case 
for (int run = 0; run < terms.Length; run++) 
{
    terms[run] = 400;
}

//print value from each of the index
for (int run = 0; run < terms.Length; run++)
{
    Console.WriteLine("Value in index {0}:\t{1}",run, terms[run]);
}

Console.ReadLine();

/ *输出: 索引0中的值:400 索引1中的值为400 索引2中的值为400 索引3中的值为400 索引4中的值为400 索引5中的值为400 索引6中的值为400 索引7中的值为400 索引8中的值为400 索引9中的值为400 * /

int[] terms = new int[400];

for(int runs = 0; runs < 400; runs++)
{
    terms[runs] = value;
}

使用Linq的方法,Concat使这变得简单

int[] array = new int[] { 3, 4 };

array = array.Concat(new int[] { 2 }).ToArray();

结果 3、4、2

我将为另一个变体添加这个。我更喜欢这种类型的函数编码行。

Enumerable.Range(0, 400).Select(x => x).ToArray();

你不能简单地向数组中添加一个元素。您可以将元素设置在给定位置,如fallen888所述,但我建议使用List<int>或Collection<int>,如果需要将其转换为数组,则使用ToArray()。