有没有办法在修改其元素之前不必指定数组大小?
Is there any way to not have to specify an array size before modifying its elements?
假设我想在 int[] 中写入一个值,但我还不知道该数组的长度。
目前,我只是 运行 我使用的任何算法一次来获取数组的长度,然后我实例化数组,最后 运行 相同的算法修改数组的元素.
这是一个代码示例:
for (int i = 0; i < input.length; i++)
{
if (i == condition)
{
length++;
}
}
array = new int[length];
for (int i = 0; i < input.length; i++)
{
if (i == condition)
{
array[i] = whatever;
}
}
只需使用列表
List<string> list = new List<string>();
添加元素时只需执行:
list.Add("Hello, world!");
您不需要为列表指定长度,您可以添加任意数量的元素
https://www.c-sharpcorner.com/article/c-sharp-list/
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-6.0
假设我想在 int[] 中写入一个值,但我还不知道该数组的长度。
目前,我只是 运行 我使用的任何算法一次来获取数组的长度,然后我实例化数组,最后 运行 相同的算法修改数组的元素.
这是一个代码示例:
for (int i = 0; i < input.length; i++)
{
if (i == condition)
{
length++;
}
}
array = new int[length];
for (int i = 0; i < input.length; i++)
{
if (i == condition)
{
array[i] = whatever;
}
}
只需使用列表
List<string> list = new List<string>();
添加元素时只需执行:
list.Add("Hello, world!");
您不需要为列表指定长度,您可以添加任意数量的元素
https://www.c-sharpcorner.com/article/c-sharp-list/
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-6.0