可能是一个非常简单的一个-我开始用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 ArraySize = 400;

int[] terms = new int[ArraySize];


for(int runs = 0; runs < ArraySize; runs++)
{

    terms[runs] = runs;

}

这就是我的编码方式。

其他回答

c#数组是固定长度的,并且总是有索引。遵循Motti的解决方案:

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

请注意,这个数组是一个密集数组,一个400字节的连续块,您可以在其中删除内容。如果你想要一个动态大小的数组,使用List<int>。

List<int> terms = new List<int>();
for(int runs = 0; runs < 400; runs ++)
{
    terms.Add(runs);
}

int[]和List<int>都不是关联数组——这在c#中是Dictionary<>。数组和列表都是密集的。

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 * /

         static void Main(string[] args)
        {
            int[] arrayname = new int[5];/*arrayname is an array of 5 integer [5] mean in array [0],[1],[2],[3],[4],[5] because array starts with zero*/
            int i, j;


          /*initialize elements of array arrayname*/
            for (i = 0; i < 5; i++)
            {
                arrayname[i] = i + 100;
            }

             /*output each array element value*/
            for (j = 0; j < 5; j++)
            {
                Console.WriteLine("Element and output value [{0}]={1}",j,arrayname[j]);
            }
            Console.ReadKey();/*Obtains the next character or function key pressed by the user.
                                The pressed key is displayed in the console window.*/
        }

正如其他人所描述的那样,使用List作为中介是最简单的方法,但由于您的输入是一个数组,并且您不希望将数据保存在List中,因此我假定您可能关心性能。

最有效的方法可能是分配一个新数组,然后使用array。Copy或Array.CopyTo。如果你只是想在列表的末尾添加一个项目,这并不难:

public static T[] Add<T>(this T[] target, T item)
{
    if (target == null)
    {
        //TODO: Return null or throw ArgumentNullException;
    }
    T[] result = new T[target.Length + 1];
    target.CopyTo(result, 0);
    result[target.Length] = item;
    return result;
}

如果需要,我还可以发布以目标索引作为输入的Insert扩展方法的代码。它稍微复杂一点,使用静态方法Array。复制1-2次。

如果你用c# 3编写代码,你可以用一行代码来实现:

int[] terms = Enumerable.Range(0, 400).ToArray();

这段代码片段假设您有一个System的using指令。Linq在你的文件顶部。

另一方面,如果您正在寻找可以动态调整大小的东西,这似乎是PHP的情况(我实际上从未学习过它),那么您可能希望使用List而不是int[]。下面是代码的样子:

List<int> terms = Enumerable.Range(0, 400).ToList();

但是请注意,不能通过设置terms[400]来简单地添加第401个元素。相反,你需要像这样调用Add():

terms.Add(1337);