数组存储相同类型元素的固定大小顺序集合.数组用于存储数据集合,但将数组视为存储在连续内存位置的相同类型变量的集合通常更有用.
而不是声明单个变量,例如number0,number1,...和number99,你声明一个数组变量,如数字,并使用数字[0],数字[1]和...,数字[99]来表示单个变量.索引访问数组中的特定元素.
所有数组都包含连续的内存位置.最低地址对应第一个元素,最高地址对应最后一个元素.
声明数组
要在C#中声明数组,可以使用以下语法 :
datatype[] arrayName;
其中,
数据类型用于指定数组中元素的类型.
[] 指定数组的等级.等级指定数组的大小.
arrayName 指定数组的名称.
例如,
double[] balance;
初始化数组
声明数组不会初始化内存中的数组.初始化数组变量时,可以为数组赋值.
Array是一种引用类型,因此您需要使用 new 关键字来创建一个数组的实例.例如,
double[] balance = new double[10];
为数组赋值
您可以使用索引号为各个数组元素赋值,例如 :
double[] balance = new double[10];balance[0] = 4500.0;
您可以在声明时为数组指定值,如下所示 :
double[] balance = { 2340.0, 4523.69, 3421.0};
你也可以创建和初始化一个数组,如图所示 :
int [] marks = new int[5] { 99, 98, 92, 97, 95};
您也可以省略数组的大小,如下所示&减去;
int [] marks = new int[] { 99, 98, 92, 97, 95};
您可以将数组变量复制到另一个目标数组变量中.在这种情况下,目标和源都指向相同的内存位置 :
int [] marks = new int[] { 99, 98, 92, 97, 95};int[] score = marks;
创建数组时,C#编译器会根据数组类型隐式地将每个数组元素初始化为默认值.例如,对于int数组,所有元素都初始化为0.
访问数组元素
通过索引数组名称来访问元素.这是通过将元素的索引放在数组名称后面的方括号中来完成的.例如,
double salary = balance[9];
以下示例演示了上述概念声明,赋值和访问数组 :
using System;namespace ArrayApplication { class MyArray { static void Main(string[] args) { int [] n = new int[10]; /* n is an array of 10 integers */ int i,j; /* initialize elements of array n */ for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; } /* output each array element's value */ for (j = 0; j < 10; j++ ) { Console.WriteLine("Element[{0}] = {1}", j, n[j]); } Console.ReadKey(); } }}
编译并执行上述代码时,会产生以下结果 :
Element[0] = 100Element[1] = 101Element[2] = 102Element[3] = 103Element[4] = 104Element[5] = 105Element[6] = 106Element[7] = 107Element[8] = 108Element[9] = 109
使用 foreach 循环
在前面的例子中,我们使用for循环来访问每个数组元素.您还可以使用 foreach 语句迭代数组.
using System;namespace ArrayApplication { class MyArray { static void Main(string[] args) { int [] n = new int[10]; /* n is an array of 10 integers */ /* initialize elements of array n */ for ( int i = 0; i < 10; i++ ) { n[i] = i + 100; } /* output each array element's value */ foreach (int j in n ) { int i = j-100; Console.WriteLine("Element[{0}] = {1}", i, j); } Console.ReadKey(); } }}
编译并执行上述代码时,会产生以下结果 :
Element[0] = 100Element[1] = 101Element[2] = 102Element[3] = 103Element[4] = 104Element[5] = 105Element[6] = 106Element[7] = 107Element[8] = 108Element[9] = 109
C#数组
有以下与数组相关的一些重要概念应该对C#程序员清楚&减去;
Sr.No. | 概念&说明 |
---|---|
1 | 多维数组 C#支持多维数组.多维数组的最简单形式是二维数组. |
2 | Param数组中 b $ b 这用于将未知数量的参数传递给函数. |
5 | 数组类 在System命名空间中定义,它是所有数组的基类,并提供各种属性以及使用数组的方法. |