在进行批量处理数据的时候,我们要用到数组。数组是一组类型相同的有序数据。数组按照数组名、数据元素的类型和维数来进行描述。C#中提供System.Array类是所有数组类型的基类。
数组的声明格式:
non-array-type[ dim-separators ] array-instance name;
比如我们声明一个整数数组:
int[] arr;
在定义数组的时候,可以预先指定数组元素的个数,这时在“[]”中定义数组的元素个数,它的个数可以通过数组名加圆点加“Length”获得。而在使用数组的时候,可以在“[]”中加入下标来取得对应的数组元素。C#中的数组元素的下标是从0开始的,也就是说,第一个元素对应的下标为0,以后逐个增加。
在C#中数组可以是一维的也可以是多维的,同样也支持矩阵和参差不齐的数组。一维数组最为普遍,用的也最多。我们先看一看下面的例子:
程序清单4-3:
using System:
class Test
{
static void Main(){
int[] arr=new int[5];
for(int i=0;i〈arr.Length;i++)
arr[i]=i*i;
for(int i=0;i〈arr.Length;i++)
Console.WriteLine("arr[{0}]={1}",i,arr[i]);
}
}
这个程序创建了一个基类型为int型的一维数组,初始化后逐项输出。其中arr.Length表示数组元素的个数。程序的输出为:
arr[0]=0
arr[1]=1
arr[2]=4
arr[3]=9
arr[4]=16
上面的例子中我们用的是一维的,很简单吧!下面我们介绍多维的:
class Text
{
static void Main(){ //可动态生成数组的长度
string[] a1; //一维string数组
string[,] a2 //二维
string[,,] a3 //三维
string[][] j2; //可变数组(数组)
string[][][][] j3; //多维可变数组
}
在数组声明的时候可以对数组元素进行赋值,或者叫做对数组的初始化。也可以在使用的时候进行动态赋值。看下面的例子:
class Test
{
static void Main(){
int[] a1=new int[] {1,2,3};
int[,] a2=new int[,] {{1,2,3},{4,5,6}};
int[,,] a3=new int[10,20,30];
int[][] j2=new int[3][];
j2[0]=new int[] {1,2,3};
j2[1]=new int[] {1,2,3,4,5,6};
j2[2]=new int[] {1,2,3,4,5,6,7,8,9};
}
}
上面的例子我们可以看出数组初始化可以用几种不同的类型,因为它要求在一个初始化时要确定其类型。比如下面的写法是错误的:
class Test
{
static void F(int[] arr){}
static void Main(){
F({1,2,3});
}
}
因为数组初始化时{1,2,3}并不是一个有效的表达式。我们必须要明确数组类型:
class Test
{
static void F(int[] arr) {}
static void Main(){
F(new int[] {1,2,3});
}
}
int [] number = {1,2,3,4,5,6,7};
int [] number = new int[5] {1,2,3,4,5};
二维数组可以声明如下:
<baseType>[,]<name>;
多维数组只需更多的逗号
<baseType>[,,,]<name>;
数组的数组
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{ //数组的数组的定义
int[][] divisors ={new int[]{1},
new int []{1,2},
new int []{1,3},
new int []{1,2,4},
new int []{1,5}};
foreach (int[] d in divisors)
{
foreach (int di in d)
{
Console.WriteLine(di);
}
}
Console.ReadKey();
}
}
}
C#允许为函数指定一个(只能指定一个)特定的参数,这个参数必须是函数定义中的最后一个参数,成为参数数组。参数数组可以使用个数不定的参数调用函数,它可以使用params关键字来定义。
params 构造函数声明数组 而不知道数组长度 用的
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static int SumVals(params int[] vals)
{
int sum = 0;
foreach(int val in vals)
{
sum += val;
}
return sum;
}
static void Main(string[] args)
{
int sum = SumVals(1,5,2,9,8);
Console.WriteLine("Summed Values = {0}",sum);
Console.ReadKey();
}
}
}