你如何在 C# 中初始化一个数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1241165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you initialize an array in C#?
提问by
How do you initialize an array in C#?
你如何在 C# 中初始化一个数组?
采纳答案by Andrew Hare
Like this:
像这样:
int[] values = new int[] { 1, 2, 3 };
or this:
或这个:
int[] values = new int[3];
values[0] = 1;
values[1] = 2;
values[2] = 3;
回答by Andreas Grech
char[] charArray = new char[10];
If you're using C# 3.0 or above and you're initializing values in the decleration, you can omit the type (because it's inferred)
如果您使用的是 C# 3.0 或更高版本并且您在 decleration 中初始化值,则可以省略类型(因为它是推断的)
var charArray2 = new [] {'a', 'b', 'c'};
回答by Mehrdad Afshari
var array = new[] { item1, item2 }; // C# 3.0 and above.
回答by Mehrdad Afshari
int [ ] newArray = new int [ ] { 1 , 2 , 3 } ;
回答by Dan
string[] array = new string[] { "a", "b", "c" };
回答by Steve
Read this
读这个
http://msdn.microsoft.com/en-us/library/aa288453%28VS.71%29.aspx
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][];