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这一keyword表示int[]是一个引用类型。在.net 3.0版本号之后。int这个keyword能够省略。可是强烈建议加上。
        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/yjbjingcha/p/7401246.html