如何C#数组初始化详解

高洛峰
Release: 2016-12-16 14:46:54
Original
1649 people have browsed it

如何初始化数组呢?这里向你详细介绍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} }; 

注意,对于交错数组的元素没有初始化语法。

C#数组初始化的相关内容就向你介绍到这里,希望对你了解和学习C#数组初始化有所帮助。



更多如何C#数组初始化详解相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!