Declare an array and assign an initial value
int[] arr = {1, 2, 3};
It can be seen that [] following the type name indicates an array, {} indicates a list of initial values to be assigned, and each initial value is separated by a comma.
Declare an array
int[] arr = new int[3]; //正确,声明一个长度为 3 的 int 类型数组 int[3] arr2; //错误,不能这样指定数组大小 int[] arr3; //没有指定数组大小,无法使用
If we don’t know the value of the array in advance, we can declare the array first as described above. Of course, we should know the type and size of the array when declaring the array. The number in [] indicates that the length is not the upper bound of the subscript.
C# arrays also support dynamic specification
int len = 3; int[] arr = new int[len];
Array assignment and value acquisition
int[] arr = new int[3]; arr[0] = 10; //给第一个元素赋值 int m = arr[0]; //取第一个元素的值
Get the array length
int[] arr = new int[3]; int len = arr.Length; int len2 = arr.GetLength(0) //这种方法也可以获取数组长度,参数表示要获取第几维的数组长度,从 0 开始。
It is more convenient to apply under .NET Framework 3.5
C# 3.0 syntax is used under .NET Framework 3.5, so use Arrays are more convenient, and you can assign values directly without specifying the length.
string[] colors = new string[]{"#333", "#666", "#999", "#ccc", "#fff"};
Declare an array colors and assign five strings to it. The length of the array here is automatically determined by the number of curly braces.
For more C# array-one-dimensional array related articles, please pay attention to the PHP Chinese website!