数组总结笔记
經常看數組每次都看自己的筆記,分享下吧。?
1.數組聲明和初始化
由于數組是引用類型,所以應該用new來初始化數組。
(1)一維
Int[] a={1,2};//這樣也可以的。
Int[] a=new int[2]{1,2};//定大小(元素個數與數組大小必須匹配)
Int[] a=new int[]{2,3,3};//由值定義大小
Int[] a=new int[size];//常量定義
Const int size=3;
(2)多維
Int[,] a=new int[2,2];
Int[,] a={{1,2},{2,3}};//
用數組初始化器(用字面值初始化)時,必須指定每個元素的值,不能遺漏。
針對一維數組可以用foreach來循環訪問每個元素。
Foreach(int I in myInt){}
(3)變長數組
注意:子數組是不能指定的,而必須分開指定。
例:Int[][] a;
a=new int[2][];
a[0]=new int[4];
a[1]=new int[5];
或 a=new int[2][]{new int[]{1,2},new int[]{3,4}};
例:int[][] a={new int[]{1,2,3},new int[]{3,3,3}};
?
2Array類
此類是作為所有數組的虛基類,當用C#語法聲明了數組,實際上就繼承了它的方法和屬性。
屬性 說明
Length 返回元素個數,返回int型,如果多維數組,返回所有階的元 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 素個數
Longlength 返回元素個數,只是用Long型返回的。
Rank 返回數組的維數
常用方法
CreateInstance(),SetValue(),Sort()
3.迭代器
迭代器的定義是,它是一個代碼塊,按順序提供了要在foreach循環中使用的所有值,一般情況下,這個代碼塊是方法,但也可以使用屬性訪問器和其代碼塊作為迭代器。
(1)如果要迭代一個類,使用方法GetEnumerator(),其返回類型是IEnumerator就可以了。
(2)如果要迭代一個類成員,例如方法,則返回類型IEnumerable。
在迭代器塊中,使用yeild關鍵字選擇要在foreach循環中使用的值。可以使用yield return;來中止返回值。
Public static IEnumerable SimpleList()//迭代一個類成員
{
Yield return “str1”;
Yield return “str2”;
}
Foreach(string item in SimpleList){}
Public IEnumerator GetEnumerator()//如果類中存在這個方法并且返回相應接口就可以迭代一個類。一般類重寫IEnumerable接口來實現,泛型和非泛型都實現
{
Yield return “ok”;
?
?
}
?
轉載于:https://www.cnblogs.com/kounian/p/3384929.html
總結
- 上一篇: cmake + visual studi
- 下一篇: 谷歌雇程序员提升开源安全