HWH....

导航

 

数组

定义

数组是一种数据结构,它包含若干相同类型的变量。数组是使用类型声明的:
type[] arrayName;
下面的示例创建一维、多维(空间)和交错数组:
class TestArraysClass
{
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 };
}
}

 

数组概述

数组可以是一维多维交错的。

数值数组元素的默认值设置为零,而引用元素的默认值设置为 null。

交错数组是数组的数组,因此,它的元素是引用类型,初始化为 null

数组的索引从零开始:具有 n 个元素的数组的索引是从 0 到 n-1

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

数组类型是从抽象基类型 Array 派生的引用类型。由于此类型实现了 System.Collections.Generic.IListSystem.Collections.Generic.ICollectionSystem.Collections.Generic.IEnumerable,因此可以对 C# 中的所有数组使用 foreach 迭代。

作为对象的数组

在 C# 中,数组实际上是对象,而不只是像 C 和 C++ 中那样的可寻址连续内存区域。Array 是所有数组类型的抽象基类型。可以使用 Array 具有的属性以及其他类成员。这种用法的一个示例是使用Length 属性来获取数组的长度。

将数组作为参数传递

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

数组可作为参数传递给方法。因为数组是引用类型,所以方法可以更改元素的值。

使用 ref 和 out 传递数组

与所有的 out 参数一样,在使用数组类型的 out 参数前必须先为其赋值

与所有的 ref 参数一样,数组类型的 ref 参数必须由调用方明确赋值。因此不需要由接受方明确赋值。可以将数组类型的 ref 参数更改为调用的结果。

要注意这两个的区别,

 示例:

代码
using System;
using System.Collections;

public class ExampleClass
{
public sealed class Path
{
private Path(){}
private static char[] badChars = {'\"', '<', '>'};
public static char[] GetInvalidPathChars()
{
return badChars;
}
}
public static void Main()
{
// The following code displays the elements of the
// array as expected.
foreach(char c in Path.GetInvalidPathChars())
{
Console.Write(c);
}
Console.WriteLine();

// The following code sets all the values to A.
Path.GetInvalidPathChars()[0] = 'A';
Path.GetInvalidPathChars()[
1] = 'A';
Path.GetInvalidPathChars()[
2] = 'A';

// The following code displays the elements of the array to the
// console. Note that the values have changed.
foreach(char c in Path.GetInvalidPathChars())
{
Console.Write(c);
}
}
}

 

 

 

posted on 2010-12-02 17:22  HWH....  阅读(260)  评论(0编辑  收藏  举报