数组是一个存储相同类型元素的固定大小的顺序集合,数组用于存储数据集合,但通常更有用的是将数组看作是存储在连续内存位置的相同类型的变量的集合。
所有数组都由连续的内存位置组成,最低地址对应于第一个元素,最高地址对应于最后一个元素。
要在C#中声明数组,可以使用以下语法-
datatype[] arrayName;
datatype 用于指定数组中元素的类型。
[] 指定数组的大小。
arrayName指定数组的名称。
double[] balance;
声明数组不会初始化内存中的数组,初始化数组变量后,可以为数组赋值。
数组是引用类型,因此您需要使用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。
通过索引数组名称来访问元素,这是通过将元素的索引放在数组名称后面的方括号内来完成的。如,
链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/csharp-arrays.html
来源:LearnFk无涯教程网
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]=100 Element[1]=101 Element[2]=102 Element[3]=103 Element[4]=104 Element[5]=105 Element[6]=106 Element[7]=107 Element[8]=108 Element[9]=109
在前面的示例中,我们使用了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]=100 Element[1]=101 Element[2]=102 Element[3]=103 Element[4]=104 Element[5]=105 Element[6]=106 Element[7]=107 Element[8]=108 Element[9]=109
下面是几个与数组相关的重要概念,C#程序员-应该清楚这些概念
Sr.No. | Concept & 描述 |
---|---|
1 |
Multi-dimensional arrays C#支持多维数组。多维数组的最简单形式是二维数组。 |
2 |
Jagged arrays C#支持多维数组,即数组的数组。 |
3 |
Passing arrays to functions 通过指定不带索引的数组名称,可以向函数传递指向数组的指针。 |
4 |
Param arrays 这用于向函数传递未知数量的参数。 |
5 |
The Array Class 在系统命名空间中定义,它是所有数组的基类,并提供用于使用数组的各种属性和方法。 |
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)