在不指定密钥C#的情况下向数组添加值

时间:2022-05-27 00:24:03

Like in PHP and some other languages, is there a way to add a value to an array without specifying the index?

就像在PHP和其他一些语言中一样,有没有办法在不指定索引的情况下向数组添加值?

int[] aWhich = {};

aWhich[] = 1;

Thanks.

谢谢。

3 个解决方案

#1


8  

Not to an Array or any other type since the indexer operator must have at least one parameter (through it does not have to be an int).

不是数组或任何其他类型,因为索引器操作符必须至少有一个参数(通过它不必是int)。

You can add to the end of a List, though:

但是,您可以添加到List的末尾:

List<int> aWhich = new List<int>();

aWhich.Add(1);

#2


0  

You can't. Arrays in C# (and .NET) are immutable (in terms of their size, not necessarely their content) and you access their values by the index. What's you are looking for is a List, ArrayList or something that might suits your need better in the System.Collections or System.Collections.Generic namespaces.

你不能。 C#(和.NET)中的数组是不可变的(就其大小而言,不一定是它们的内容),您可以通过索引访问它们的值。您正在寻找的是List,ArrayList或者在System.Collections或System.Collections.Generic命名空间中更适合您需要的东西。

#3


0  

There is one other way, Fist add elements to a List, then convert it into array.

还有另一种方法,Fist向List添加元素,然后将其转换为数组。

Eg:

例如:

var intList = new List<int>();
intList.Add(1);
intList.Add(2);

var intArray = intList.ToArray();

#1


8  

Not to an Array or any other type since the indexer operator must have at least one parameter (through it does not have to be an int).

不是数组或任何其他类型,因为索引器操作符必须至少有一个参数(通过它不必是int)。

You can add to the end of a List, though:

但是,您可以添加到List的末尾:

List<int> aWhich = new List<int>();

aWhich.Add(1);

#2


0  

You can't. Arrays in C# (and .NET) are immutable (in terms of their size, not necessarely their content) and you access their values by the index. What's you are looking for is a List, ArrayList or something that might suits your need better in the System.Collections or System.Collections.Generic namespaces.

你不能。 C#(和.NET)中的数组是不可变的(就其大小而言,不一定是它们的内容),您可以通过索引访问它们的值。您正在寻找的是List,ArrayList或者在System.Collections或System.Collections.Generic命名空间中更适合您需要的东西。

#3


0  

There is one other way, Fist add elements to a List, then convert it into array.

还有另一种方法,Fist向List添加元素,然后将其转换为数组。

Eg:

例如:

var intList = new List<int>();
intList.Add(1);
intList.Add(2);

var intArray = intList.ToArray();