如何C#数组初始化详解
如何初始化数组呢?这里向你详细介绍C#数组初始化的具体的步骤和实例演示,希望对你了解和学习如何初始化数组有所帮助,那么让我们开始吧:
C#通过将初始值括在大括号 ({}) 内为在声明时初始化数组提供了简单而直接了当的方法。特别要注意的是,如果声明时未初始化数组,则数组成员自动初始化为该数组类型的默认初始值。
下面的示例展示初始化不同类型的数组的各种方法。
C#数组初始化之一维数组
int[] numbers = new int[5] {1, 2, 3, 4, 5}; string[] names = new string[3] {"Matt", "Joanne", "Robert"};
可省略数组的大小,如下所示:
int[] numbers = new int[] {1, 2, 3, 4, 5}; string[] names = new string[] {"Matt", "Joanne", "Robert"};
如果提供了初始值设定项,还可省略 new 语句,如下所示:
int[] numbers = {1, 2, 3, 4, 5}; string[] names = {"Matt", "Joanne", "Robert"};
C#数组初始化之多维数组
int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = new string[2, 2] { {"Mike","Amy"}, {"Mary","Albert"} };
可省略数组的大小,如下所示:
int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = new string[,] { {"Mike","Amy"}, {"Mary","Ray"} };
如果提供了初始值设定项,还可省略 new 语句,如下所示:
int[,] numbers = { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = { {"Mike", "Amy"}, {"Mary", "Albert"} };
C#数组初始化之交错的数组(数组的数组)
可以像下例所示那样初始化交错的数组:
int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
可省略第一个数组的大小,如下所示:
int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
或使用
int[][] numbers = { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
相关推荐
worldsnow 2020-11-06
csdnxingyuntian 2020-11-02
丽丽 2020-10-30
bluecarrot 2020-09-17
哈嘿Blog 2020-08-16
qidiantianxia 2020-08-16
84931231 2020-07-30
ChenRuiyz 2020-07-26
yanqianglifei 2020-07-07
wbczyh 2020-07-05
BOBShe 2020-07-03
yang0cs 2020-06-28
fushilin 2020-06-28
清水寺小僧 2020-06-25
uileader 2020-06-21
wangyangsoftware 2020-06-16
cleanerxiaoqiang 2020-06-16
xuguiyi00 2020-06-14