如何在C#中初始化数组?

16 c# arrays

如何在C#中初始化数组?

And*_*are 29

像这样:

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

或这个:

int[] values = new int[3];
values[0] = 1;
values[1] = 2;
values[2] = 3;
Run Code Online (Sandbox Code Playgroud)

  • 严格来说第二种方法不叫初始化.认为读者对初始化者感兴趣. (2认同)

Meh*_*ari 16

var array = new[] { item1, item2 }; // C# 3.0 and above.
Run Code Online (Sandbox Code Playgroud)


Ste*_*eve 7

读这个

http://msdn.microsoft.com/en-us/library/aa288453%28VS.71%29.aspx

//can be any length
int[] example1 = new int[]{ 1, 2, 3 };

//must have length of two
int[] example2 = new int[2]{1, 2};           

//multi-dimensional variable length
int[,] example3 = new int[,]{ { 1, 2, 3 }, { 4, 5, 6 } };


//multi-dimensional fixed length
int[,] example4 = new int[1,2] { { 1, 2} };

//array of array (jagged)
int[][] example5 = new int[5][];
Run Code Online (Sandbox Code Playgroud)