c#基础之数组

最近看了c#的数组,比c++的数组更加直接,.net也提供了很多直接直接操纵数组的方法,非常方便,所以就想做个总结。
利用数组,我们可以使用变量来声明相同类型的多个数据项的集合,数组中的每个数据使用索引来进行唯一标识,和大多数语言一样,c#数组中的第一个数据项使用索引0访问。程序员应确保指定的索引值小于数组的大小,因为c#的数组是基于0的,所以最后一个元素的索引值总是比数组元素的总数小1。
虽然初学者应该掌握数组,但是在目前,大多数程序员使用的泛型集合而不是数组,因为泛型集合提供了更多对数据集合操纵的方法,所以在这里只是粗略的介绍下。


申明  在这里为简便起见,基本数据类型全部使用int和string类型。所有代码经过.net 4.5,vs2013测试。
1.声明:
<span style="white-space:pre"> </span>int [] myIntArray;//方括号是放在数据类型后面的,组成已成新的类类型int[],这是一个引用类型。
        int [,];//申明一个二维数组,之间要用括号,维数 = 逗号数量+1;
2.赋值:<span style="white-space:pre"> </span>int[]myIntArray = new int[3]{0,1,2};//<span style="white-space:pre">
</span>        int[] myIntArray =  new int[]{0,1,2};//这是在声明数组是就对数组进行整体赋值,要用new这一关键字表示int[]是一个引用类型。在.net 3.0版本之后,int这个关键字可以省略,但是强烈建议加上。
        int[] myIntArray =  {0,1,2}//也可以直接用字面值对数组进行初始化。
        int[] myIntArray = new int[3];//在不用字面值的情况下,必须指定数组的大小。注意 这里和c++不一样,数组的大小不一的是一个常量,可以是一个经过计算的变量。
        int [,] myMultiArray;
        myMultiArray = new int[,]{
{1,2,3},
{5,8,9},
{7,5,6}};//二维数组的初始化。
int [,]cells = {
{1,2,3},{0,1},{4}
}; //大小不一致的多维数组会造成错误。


3.交错数组:
int [][]cell =
    new int[]{1,2,3},
    new int[]{1,2},
    new int[]{3}};//交错数组定义由数组构成的数组,在代码中,int[]是数据类型,所以塔之后的[]声明了一个int[]类型的数组。

//注意 交错数组要求为内部的每个数组都创建实例,在这个例子中,我们使用new来实例化交错数组内部的元素,如果遗失这个实例化部分就会编译出错。

4.4.数组的使用 可以用方括号的方法建立索引。 5.5..NET对数组提供的API

Name.Length;//这是一个只读属性,只是这个数组的大小。

Name.Rank;//只读属性,指示这个数组的维数

Name.GetLength(int);//返回给定维数的长度,如代码

bool[,,] cells= new bool[2,3,3];

cells.Getlength(0); //这个函数的返回值为2

system.Array是所有数组的抽象基类,提供了很多操纵数组的静态方法,所以,数组是对象。

数组的其他实例方法 :Max();Min();Average();Sum();

equals(object obj);//返回两个对象是否相等

clone();浅度拷贝

静态方法:

  Array.sort();//对数组进行排序

Array.BinarySearch();//二分搜索,必须先排序。

Array.Copy();//拷贝两个数组。        

Array.Clear();//将每个元素设置为默认值。

Array.indexof();//Searches for the specified object and returns the index of the first occurrence within the entire one-dimensional 

        ArrayArray.LastIndexOf();//Searches for the specified object and returns the index of the last occurrence within the entire one-dimensional Array

Array.Reverse();//Reverses the sequence of the elements in the entire one-dimensional

Array.Reverse();Reverses the sequence of the elements in a range of elements in the one-dimensional

Array.sort(Array,Icomparer)//
Sorts the elements in a one-dimensional using the specified 
原文地址:https://www.cnblogs.com/likeFlyingFish/p/5345995.html