C#集合介面與BitArray

來源:互聯網
上載者:User

一.C#中集合的介面:ICollection

集合介面的初始化對象方式:

ICollection<Data type> mycollect=new Collection< Data type >();

現在先來看一個整數類型集合的介面

using System.Collections.ObjectMode

//必須要有這個引用
ICollection<int> myCollection = new Collection<int>();

myCollection.Add(100);//增加元素

myCollection.Add(22);

myCollection.Add(30);

foreach (int x in myCollection)

Console.WriteLine(x); //輸出元素

Console.WriteLine("集合中元素的個數{0}", myCollection.Count);

myCollection.Add(222);

myCollection.Remove(22);//刪除元素

Console.WriteLine("集合中元素的個數{0}", myCollection.Count);

Console.WriteLine(myCollection.Contains(22));//判斷集合中是否有這個元素


圖片1

判讀集合中是否存在某個元素:myCollection.Contains(x);有的話返回1,否則返回0;

將集合中的元素複製到一個同樣大小的數組中:

int[] myArray = new int[myCollection.Count];

myCollection.CopyTo(myArray, 0);//從myCollection的第一個元素開始

int[] myArray = new int[myCollection.Count];
 myCollection.CopyTo(myArray, 0);

//從myCollection的第一個元素開始

Console.WriteLine("xia現在比較下兩個對象中元素");

for (int i = 0; i < myCollection.Count; i++)

{

Console.Write("in myArray {0},",myArray[i]);

}

foreach (int x in myCollection)

Console.WriteLine("in mycollection{0}",x);


圖片2

只要按照上面介紹的方法就可以構造其他類型的泛型集合。

現在示範下另一類型的泛型集合:

ICollection<string> another = new Collection<string>();

//構造一個字串型的集合

another.Add("the ");

another.Add("people's ");

another.Add("republic ");

another.Add("china ");

foreach(string str in another)

    Console.Write(str);

該對象的輸出結果是:


圖片3

二.BitArray 

BitArray類是一個位元數組,數組的大小在建立對象的時候已經確定,每個資料元素只能表示一個位元,元素的值只能是1與0,其中用true表示1,用false表示0,當用其他資料類型的元素初始化該對象時,那麼每個元素將佔用該類型在記憶體中儲存長度的數組空間,下表中式該類提供的特殊方法:

方法名字

方法的功能

and

BitArray中的元素執行按位“與”運算

or

按位“或”運算

not

取反運算

xor

異或運算

get/set

擷取或設計特定位置處的位設定為指定值

setall

將BitArray中的所有位設定為指定值

 

初始化一個BitArray類

BitArray myBitArray = new BitArray(4);

myBitArray[0] = false;

myBitArray[1] = true;

myBitArray[2] = true;

myBitArray[3] = false;

DisplayBitArray("myBitArray", myBitArray);

Console.WriteLine("after not()之後");

myBitArray.Not();

DisplayBitArray("myBitArray", myBitArray);


圖片4

當然這裡還定義了一個方法專門用來輸出:

public static void DisplayBitArray(string arrayListName, BitArray myBitArray)

{ for (int i = 0; i < myBitArray.Count; i++)

{

    Console.WriteLine(arrayListName + "[" + i + "] = " + myBitArray[i]);

}

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.