VB.NET集合另類使用方法詳解
通過對VB.NET的深入解讀,可以知道,它并不僅僅是一個版本的升級,它的作用為大家?guī)矸浅6嗟暮锰帯T谶@里我們可以通過對VB.NET集合的不同的使用方法來解讀這門語言的具體應(yīng)用技巧。#t#
盡管VB.NET集合一般是用來處理 Object 數(shù)據(jù)類型的,但它也可以用來處理任何數(shù)據(jù)類型。有時用集合存取數(shù)據(jù)比用數(shù)組更加有效。
如果需要更改數(shù)組的大小,必須使用 ReDim 語句 (Visual Basic)。當(dāng)您這樣做時,Visual Basic 會創(chuàng)建一個新數(shù)組并釋放以前的數(shù)組以便處置。這需要一定的執(zhí)行時間。因此,如果您處理的項數(shù)經(jīng)常更改,或者您無法預(yù)測所需的最大項數(shù),則可以使用集合來獲得更好的性能。
集合不用創(chuàng)建新對象或復(fù)制現(xiàn)有元素,它在處理大小調(diào)整時所用的執(zhí)行時間比數(shù)組少,而數(shù)組必須使用 ReDim。但是,如果不更改或很少更改大小,數(shù)組很可能更有效。一直以來,性能在很大程度上都依賴于個別的應(yīng)用程序。您應(yīng)該花時間把數(shù)組和集合都嘗試一下。
專用VB.NET集合
下面的示例使用 .NET Framework 泛型類 System.Collections.Generic..::.List<(Of <(T>)>) 來創(chuàng)建 customer 結(jié)構(gòu)的列表集合。
代碼
- ' Define the structure for a
customer.- Public Structure customer
- Public name As String
- ' Insert code for other members
of customer structure.- End Structure
- ' Create a module-level collection
that can hold 200 elements.- Public custFile As New List
(Of customer)(200)- ' Add a specified customer
to the collection.- Private Sub addNewCustomer
(ByVal newCust As customer)- ' Insert code to perform
validity check on newCust.- custFile.Add(newCust)
- End Sub
- ' Display the list of
customers in the Debug window.- Private Sub printCustomers()
- For Each cust As customer
In custFile- Debug.WriteLine(cust)
- Next cust
- End Sub
注釋
custFile 集合的聲明指定了它只能包含 customer 類型的元素。它還提供 200 個元素的初始容量。過程 addNewCustomer 檢查新元素的有效性,然后將新元素添加到集合中。過程 printCustomers 使用 For Each 循環(huán)來遍歷集合并顯示VB.NET集合的元素。