在不初始化长度的情况下向数组添加值

Hse*_*ung 2 c# arrays initialization

当我可以向数组添加值时,会发生异常.在C#中,我可以在不初始化数组长度的情况下设置值.

int[] test;
test[0] = 10;
Run Code Online (Sandbox Code Playgroud)

jas*_*son 11

No, if you want a data structure that dynamically grows as you Add items, you will need to use something like List<T>. Arrays are fixed in size.

When you have

int[] test;
Run Code Online (Sandbox Code Playgroud)

you haven't instantiated an array, you've merely declared that test is a variable of type int[]. You need to also instantiate a new array via

int[] test = new int[size];
Run Code Online (Sandbox Code Playgroud)

As long as size is positive then you can safely say

int[0] = 10;
Run Code Online (Sandbox Code Playgroud)

In fact, you can say

int[index] = 10
Run Code Online (Sandbox Code Playgroud)

as long as 0 <= index < size.

Additionally, you can also declare, instantiate and initialize a new array in one statement via

int[] test = new int[] { 1, 2, 3, 4 };
Run Code Online (Sandbox Code Playgroud)

Note that here you do not have to specify the size.