2.C#编程指南-数组

简介

数组是一种数据结构,它包含若干相同类型的变量。数组是使用类型声明的:

type[] arrayName;

1.数组可以是一维、多维或交错的。

View Code
//一维数组
int[] array = {1,2,3}
//多维数组
int[,] array = {{1,2},{3,4},{5,6}};
//交错数组:元素为数组的数组,因此其元素是引用类型并初始化为null。
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[3];

2.数值数组元素的默认值设置为0,而引用元素的默认值设置为null

3.交错数组是数组的数组,因此其元素是引用类型并初始为null

4.数组的索引从0开始:具有n个元素的数组的索引从0到n-1。

5.数组元素可以是任何类型,包括数组类型。

6.数组类型是从抽象基类型Array派生的引用类型。由于此类型实现了IEnumberable和IEnumberable(Of T),因些可以对C#中的所有数组使用foreach迭代。

 

作为对象的数组

在C#中,数组实际上是对象。Array是所有数组类型的抽象基类型。可以使用Array具有的属性以及其他类成员。

这种用法的一个示例是使用Length属性来获取数组的长度。

int[] numbers = {1,2,3,4,5};
int lengthOfNumbers = numbers.Length;

Array类提供了许多其他有用的方法和属性,用于排序搜索复制数组。

 

将数组作为参数传递(ChangeArray??)

View Code
class ArrayClass
{
static void PrintArray(string[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
System.Console.Write(arr[i] + "{0}", i < arr.Length - 1 ? " " : "");
}
System.Console.WriteLine();
}

static void ChangeArray(string[] arr)
{
// The following attempt to reverse the array does not persist when
// the method returns, because arr is a value parameter.
arr = (arr.Reverse()).ToArray();
// The following statement displays Sat as the first element in the array.
System.Console.WriteLine("arr[0] is {0} in ChangeArray.", arr[0]);
}

static void ChangeArrayElements(string[] arr)
{
// The following assignments change the value of individual array
// elements.
arr[0] = "Sat";
arr[1] = "Fri";
arr[2] = "Thu";
// The following statement again displays Sat as the first element
// in the array arr, inside the called method.
System.Console.WriteLine("arr[0] is {0} in ChangeArrayElements.", arr[0]);
}

static void Main()
{
// Declare and initialize an array.
string[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

// Pass the array as an argument to PrintArray.
PrintArray(weekDays);

// ChangeArray tries to change the array by assigning something new
// to the array in the method.
ChangeArray(weekDays);

// Print the array again, to verify that it has not been changed.
System.Console.WriteLine("Array weekDays after the call to ChangeArray:");
PrintArray(weekDays);
System.Console.WriteLine();

// ChangeArrayElements assigns new values to individual array
// elements.
ChangeArrayElements(weekDays);

// The changes to individual elements persist after the method returns.
// Print the array, to verify that it has been changed.
System.Console.WriteLine("Array weekDays after the call to ChangeArrayElements:");
PrintArray(weekDays);
}
}
// Output:
// Sun Mon Tue Wed Thu Fri Sat
// arr[0] is Sat in ChangeArray.
// Array weekDays after the call to ChangeArray:
// Sun Mon Tue Wed Thu Fri Sat
//
// arr[0] is Sat in ChangeArrayElements.
// Array weekDays after the call to ChangeArrayElements:
// Sat Fri Thu Wed Thu Fri Sat

posted on 2012-03-21 16:35  YeChun  阅读(201)  评论(0编辑  收藏  举报

导航