VB.NET集合另類使用方法詳解
通過(guò)對(duì)VB.NET的深入解讀,可以知道,它并不僅僅是一個(gè)版本的升級(jí),它的作用為大家?guī)?lái)非常多的好處。在這里我們可以通過(guò)對(duì)VB.NET集合的不同的使用方法來(lái)解讀這門語(yǔ)言的具體應(yīng)用技巧。#t#
盡管VB.NET集合一般是用來(lái)處理 Object 數(shù)據(jù)類型的,但它也可以用來(lái)處理任何數(shù)據(jù)類型。有時(shí)用集合存取數(shù)據(jù)比用數(shù)組更加有效。
如果需要更改數(shù)組的大小,必須使用 ReDim 語(yǔ)句 (Visual Basic)。當(dāng)您這樣做時(shí),Visual Basic 會(huì)創(chuàng)建一個(gè)新數(shù)組并釋放以前的數(shù)組以便處置。這需要一定的執(zhí)行時(shí)間。因此,如果您處理的項(xiàng)數(shù)經(jīng)常更改,或者您無(wú)法預(yù)測(cè)所需的最大項(xiàng)數(shù),則可以使用集合來(lái)獲得更好的性能。
集合不用創(chuàng)建新對(duì)象或復(fù)制現(xiàn)有元素,它在處理大小調(diào)整時(shí)所用的執(zhí)行時(shí)間比數(shù)組少,而數(shù)組必須使用 ReDim。但是,如果不更改或很少更改大小,數(shù)組很可能更有效。一直以來(lái),性能在很大程度上都依賴于個(gè)別的應(yīng)用程序。您應(yīng)該花時(shí)間把數(shù)組和集合都嘗試一下。
專用VB.NET集合
下面的示例使用 .NET Framework 泛型類 System.Collections.Generic..::.List<(Of <(T>)>) 來(lái)創(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 個(gè)元素的初始容量。過(guò)程 addNewCustomer 檢查新元素的有效性,然后將新元素添加到集合中。過(guò)程 printCustomers 使用 For Each 循環(huán)來(lái)遍歷集合并顯示VB.NET集合的元素。















 
 
 
 
 
 
 