【发布时间】:2017-07-29 10:02:00
【问题描述】:
如何在 C# 中初始化数组?
【问题讨论】:
如何在 C# 中初始化数组?
【问题讨论】:
像这样:
int[] values = new int[] { 1, 2, 3 };
或者这个:
int[] values = new int[3];
values[0] = 1;
values[1] = 2;
values[2] = 3;
【讨论】:
var array = new[] { item1, item2 }; // C# 3.0 and above.
【讨论】:
阅读本文
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][];
【讨论】:
char[] charArray = new char[10];
如果您使用 C# 3.0 或更高版本并且您在声明中初始化值,则可以省略类型(因为它是推断出来的)
var charArray2 = new [] {'a', 'b', 'c'};
【讨论】:
int [ ] newArray = new int [ ] { 1 , 2 , 3 } ;
【讨论】:
string[] array = new string[] { "a", "b", "c" };
【讨论】: