adding values to the array without initialization the length
When I can add values to the array , Exception occurs. In C# , can i set the values wit开发者_StackOverflow中文版hout initializing the array length.
int[] test;
test[0] = 10;
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;
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];
As long as size
is positive then you can safely say
int[0] = 10;
In fact, you can say
int[index] = 10
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 };
Note that here you do not have to specify the size.
You can't do that with an array, per se, but you can use a List.
List<int> test = new List<int>();
test.Add(10);
Only that way
int[] a = {10};
But the length of the array will be 1 after that.
Try
int[] x = new int[] { 1, 2, 3, 4 };
Use List<int> t = new List<int>()
and use t.Add()
method.
you can use this way
string[] words;
words = new List<string>() { "hello","hi" }.ToArray()
精彩评论