C# 一维 多维 交叉数组
2011-10-14 10:19 Eric.Hu 阅读(885) 评论(1) 编辑 收藏 举报数组是一种数据结构,它包含若干相同类型的变量。数组是使用类型声明的:
type[] arrayName;
下面的示例创建一维、多维和交错数组:
{
static void Main()
{
// Declare a single-dimensional array
int[] array1 = new int[5];
// Declare and set array element values
int[] array2 = new int[] { 1, 3, 5, 7, 9 };
// Alternative syntax
int[] array3 = { 1, 2, 3, 4, 5, 6 };
// Declare a two dimensional array
int[,] multiDimensionalArray1 = new int[2, 3];
// Declare and set array element values
int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };
// Declare a jagged array
int[][] jaggedArray = new int[6][];
// Set the values of the first array in the jagged array structure
jaggedArray[0] = new int[4] { 1, 2, 3, 4 };
}
}
在 C# 中,数组实际上是对象,而不只是像 C 和 C++ 中那样的可寻址连续内存区域。Array 是所有数组类型的抽象基类型。可以使用 Array 具有的属性以及其他类成员。这种用法的一个示例是使用 Length 属性来获取数组的长度。
数组可以具有多个维度。例如,下列声明创建一个四行两列的二维数组:
int[,] array = new int[4, 2];
下列声明创建一个三维(4、2 和 3)数组:
int[, ,] array1 = new int[4, 2, 3];
初始化数组:
int[, ,] array3D = [,,] { { { , , } }, { { , , newint123456 } } };
交错数组是元素为数组的数组。交错数组元素的维度和大小可以不同。交错数组有时称为“数组的数组”。以下示例说明如何声明、初始化和访问交错数组。
下面声明一个由三个元素组成的一维数组,其中每个元素都是一个一维整数数组:
int[][] jaggedArray = new int[3][];
初始化数组
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
或
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };
或
{
new int[] {1,3,5,7,9},
new int[] {0,2,4,6},
new int[] {11,22}
};
不能从元素初始化中省略 new 运算符,因为不存在元素的默认初始化,交错数组是数组的数组,因此其元素是引用类型并初始化为 null。
交错数组示例 :
{
static void Main()
{
// Declare the array of two elements:
int[][] arr = new int[2][];
// Initialize the elements:
arr[0] = new int[5] { 1, 3, 5, 7, 9 };
arr[1] = new int[4] { 2, 4, 6, 8 };
// Display the array elements:
for (int i = 0; i < arr.Length; i++)
{
System.Console.Write("Element({0}): ", i);
for (int j = 0; j < arr[i].Length; j++)
{
System.Console.Write("{0}{1}", arr[i][j], j == (arr[i].Length - 1) ? "" : " ");
}
System.Console.WriteLine();
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
/* Output:
Element(0): 1 3 5 7 9
Element(1): 2 4 6 8
*/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器