Collection-collection class in VB

Source: Internet
Author: User

Because it is difficult to process some dataAlgorithmTo process a large number of different types of data.

Therefore, considering some factors, VB6 is used again (unfortunately, Microsoft does not support VB6 and changed to the DOTNET framework). Therefore, it is best to use the collection set (class) that comes with VB6.

In fact, collection also has a one-to-one relationship between key and value. There is also the ID order.

Isn't the key-value database popular now? If collection can be saved to files, will it be perfect soon ?? Anyway, it is still good to use the database that processes data in real time as the key value.

It is convenient to create a collection from "class generator utility" in VB6. The only inconvenience is that collection is not used as a class by default. Is this actually a class. Generally, a collection can only have one row and multiple elements are added. But you can also create multiple collections, that is, there are Collections Under the collection, there are some classes, the complexity is a little higher.

The following is an example of a simple collection with a class.

 
'Filename: onekeycls. CLs
Option ExplicitPublicKeyAs String
 'Filename: onekeycol. CLs
Option Explicit ' Local variables: Save the set Private Mcol As Collection Public Function Add (Key As String , Optional Skey As String ) As Onekeycls ' Create new object Dim Objnewmember As Onekeycls Set Objnewmember = New Onekeycls ' Set the attributes of the Input Method Objnewmember. Key = Key If Len (Skey) = 0 Then Mcol. Add objnewmember Else Mcol. Add objnewmember, skey End If ' Returns the created object. Set Add = Objnewmember Set Objnewmember = Nothing End Function ' The following error is handled! If no keyword exists, the system will return nothing. Public Property Get Item (vntindexkey As Variant) As Onekeycls err. Clear On Error Goto Getitemerror ' Used to reference an element in a set. ' Vntindexkey contains the index or Keyword of the set, ' This is why variant is declared. ' Syntax: Set Foo = x. Item (XYZ) or set Foo = x. Item (5) Set Item = Mcol (vntindexkey) Exit Property Getitemerror: Debug. Print err. Source & " : Error was found in item (vntindexkey as variant) as onekeycls. " & Vbcrlf & err. Description & " : " & Err. Number Set Item = Nothing End Property Public Property Get Count () As Long ' Used to retrieve the number of elements in a set. Syntax: Debug. Print X. Count Count = Mcol. Count End Property Public Sub Remove (vntindexkey As Variant) ' Used to delete elements in a set. ' Vntindexkey contains indexes or keywords, which is why it should be declared as Variant ' Syntax: X. Remove (XYZ) Mcol. Remove vntindexkey End sub Public Property Get Newenum () As Iunknown ' This attribute allows you to use the for... each syntax to enumerate the set. Set Newenum = Mcol. [_ newenum] End Property Private Sub Class_initialize () ' Create a set after creating a class Set Mcol = New Collection End sub Private Sub Class_terminate () ' Destroys the set after the class ends. Set Mcol = Nothing End sub

Example:

     Dim Cars As   New  Onekeycol cars. Add  "  10.1  " , "  2  " Cars. Add  "  10.2  " , "  20  "  Cars. Add  "  10.3  " , "  200  "  Cars. Add  "  Key "  Debug. Print  "  Count:  " & Cars. Count Debug. Print cars. Item (  "  200  "  ). Key Debug. Print  Typename (Cars. Item ( "  300  " )) ' Error nothing              Dim  I  Dim Key1 As  Onekeycls  '  Traversing by index is less efficient than the following method      For I = 1   To  Cars. Count  Set Key1 = Cars. Item (I) Debug. Print key1.key  Next         '  This Traversal method is recommended.      For   Each Key1 In  Cars Debug. Print key1.key  Next 

 

 

Below we will try to repost the collection of VB6.

 

Visual Basic collection object ()
A set is a method used to group A series of related items. Visual Basic integration can be used to track many things, suchProgramThe loaded form (Form set), or all controls (control set) in the form ).
The Collection class provided by Visual Basic can be used to define its own set. You can create a collection object, that is, an instance of the Collection class. You can also use a collection object as the basis for your collection class and object model. It will be discussed in "create your own collection class" and "Object Model" later in this chapter.
For example, a set is the best way to track multiple forms. In the "Create User Interface" section "Multi-Document Interface (MDI) Application", we will discuss the applications that users can open any number of document windows. BelowCodeSection shows how to use the add method of the collection object to manage the list of user-created MDI child forms. This Code assumes that a form named mdidocument already exists, and its mdichild attribute is set to true.
'Module-level set in the parent mdiform.

 Public Coldocuments As   New  Collection  '  Create a new MDI sub-document form code. Private   Sub  Mnufilenew ()  Dim F As   New  Mdidocument  Static Intdocumentnumber As   Integer  Intdocumentnumber = Intdocumentnumber 1  '  The following statement creates a form. F. Caption = " Document  " & Intdocumentnumber  '  Add an object reference to the set.  Coldocuments. Add ff. Show  End sub 

Coldocuments acts as a subset of the built-in form set. It only contains some instances of the form mdidocument. Each time a new form is added, the size of the set is automatically adjusted. You can use for each... next to iterate in the set. If the form is assigned a searchable key, a text string can be provided as the second parameter of the add method, as described in later sections of this section.

In the Declaration of the variable coldocuments, The New Keyword causes the set object to be created in the code when the variable is referenced for the first time. Because the set is a class rather than a data type, you must create a collection instance and record the reference to this instance (object) in the variable.
Like any other object, when the last variable containing its reference is set to nothing or invisible, the collection object will be withdrawn. All object references contained in it will be released. Therefore, the variable coldocuments is declared in the parent mdiform, so it will exist in the entire process of program survival.
Note: If you use a set to track a form, you should use the Remove Method of the set to delete this object reference from the set after the form is detached. As long as the reference to the form still exists, the memory used by the form cannot be reclaimed, and the reference stored in the collection object is as intact as the reference in the object variable.

Composition of collection objects

Each collection object is stored in a variants object. Therefore, the list of content that can be added to the Collection object is the same as the list of content that can be stored in variants. This includes standard data types, objects, and Arrays-but does not include user-defined types.
Regardless of what is stored in variants, it occupies 16 bytes, so using collection objects is not as efficient as using arrays. However, you cannot redim a collection object, redim collection Objects make the code clearer and easier to maintain. In addition, keys of the Set object can be quickly searched, but arrays cannot.
To be accurate, even if data is stored elsewhere, variants always occupies only 16 bytes. For example, if you assign a string or array to variants, variants contains a pointer to the string and array data backup. In a 32-bit system, the pointer only uses four bytes of variants, and there is no data in variants.
To store an object, variants will include the object reference, just as the object variable does. For strings and arrays, only four bytes of variants are used.
The numeric data type is stored in variants. Regardless of the Data Type, variants still occupies 16 bytes.
In addition to the variants size, there are many cases where collection objects need to be used to store all the data types listed above. You should be aware of the trade-offs: Use collection objects to Write clear and easy-to-maintain code-only save some items in variant.

Attributes and methods of collection objects

Each set object has attributes and methods that can be used to insert, delete, and retrieve items in the set.

Attribute or method description add an item to the set. The Count attribute returns the number of items in the set. Read-only. The item method returns an item through an index or keyword. The Remove Method deletes items from the set by using indexes or keywords.

These attributes and methods are just the most basic functions of a set. For example, to ensure that the set contains only one object, the add method does not check the object type to be added to the set. By creating your own collection classes, you can provide more robust functions, as well as additional attributes, methods, and events, as described in "create your own collection classes" later in this chapter.

The basic functions of adding, deleting, and searching in a set require keywords and indexes. The keyword is a string value. It can be a string name, driver's license number, social security number, or a simple integer. The add method allows you to associate keywords with items, as described later in this section.
The index is a long integer between 1 and the number of items in the set. You can use the before and after parameters to control the initial values of the index. However, as other items are added and deleted, their values change.
Note that the set where the index starts from 1 is called based on 1, as described in "collection in Visual Basic.
You can use indexes to iterate over items in a set. For example, assuming that the variable mcolemployees contains a reference to the collection object, the following code uses two methods to increase the salary of all employees in the employee object set by 10%.

DimLngctAs LongForLngct =1 ToMcolemployees. countmcolemployees (lngct). Rate=_ Mcolemployees (lngct). Rate*1.1NextDimEMPAsEmployeeFor EachEMPInMcolemployeesemp. Rate= EMP. rate *1.1Next

 

Prompt to improve performance,Use for each to iterate items in the collection object.. Using for each iterations is much faster than using indexes. This is not true for all sets-it depends on how the set stores data.

Add items to the set
The add method is used to add an item to a set. Syntax:

 
SubAdd (itemAsVariant [, keyAsVariant] [, beforeAsVariant] [, afterAsVariant])

For example, you can use the work order ID attribute as a keyword to add a work order object to the work order set. The code can be written as follows:

 
Colworkorders. Add wonew, wonew. ID

It is assumed that the ID attribute is a string. If the attribute is a number (such as long), use the CSTR function to convert it to the string value required by the Keyword:

 
Colworkorders. Add wonew,CSTR(Wonew. ID)

The add method supports named parameters. To add a third element, the code can be written as follows:

Colworkorders. Add wonew, wonew. ID, after: =2

You can use the parameters named before and after to manage ordered object sets. For example, before: = 1 inserts an item at the beginning of the set, because the set object is based on 1.

Delete an item from a collection
The remove method is used to delete items from the set. Syntax:

 
Object. Remove Index

The index parameter can be the location of the deleted item in the set or the keyword of the item. If the keyword of the third element in the set is "w017493", you can use either of the two statements to delete it:

 
Colworkorders. Remove3-Or-Colworkorders. Remove"W017493"

 

Retrieve items from a collection

The item method is used to retrieve a specific item from the set. Syntax:

 
[Set] Variable =Object. Item (INDEX)

Like the Remove Method, index can retrieve the position of an item in the set or the keyword of the item. Using the same example in the Remove Method, any of the two statements can retrieve the third element in the Set:

 
SetWocurrent = colworkorders. Item (3)-Or-SetWocurrent = colworkorders. Item ("W017493")

If integers are used as keywords, you must use the CSTR function to convert them to strings before passing them to the item or remove method. Generally, the set object assumes that the integer is an index.

The system prompts that the collection object cannot determine whether the passed value is an index or a key. If you want to interpret a value as a key and the variable containing this value is any value other than string, you can use the CSTR function for conversion. If you want to interpret the value as an index and the variable containing this value is not one of the integer data types, use clng for conversion.
Item is the default method.
For a collection object, the item method is the default method. Therefore, you can ignore it when accessing an item in the set. The preceding code example can also be written as follows:

SetWocurrent = colworkorders (3)-Or-SetWocurrent = colworkorders ("W017493")

When a collection object element is added or deleted, the set object automatically maintains its digital index number. Therefore, the numeric index of the given element changes accordingly. You cannot store the numeric index value in a program and use it to retrieve the same element. For this purpose, the key should be used.

 

Use the item method to call attributes and Methods
To use object reference, you cannot retrieve the object reference from the set and place it in the object variable. The object can be referenced when it is still in the set.
For example, assume that the workorder object in the above Code has the priority attribute. The following statements can be used to set the priority of a work order:

Colworkorders. Item ("W017493"). Priority =3Colworkorders ("W017493"). Priority =3

The reason is that Visual Basic calculates the expression from left to right. When the item method is encountered-explicitly or implicitly-Visual Basic is the specified item (in this case, it is the workorder object with the key w017493) to get a reference, use this reference to calculate the remaining parts of the row.

If you want to call multiple attributes or methods of an object in a collection, copy the object reference to a strongly typed object variable. Placing references in a strongly typed object variable is faster than using the reference of objects in the Set (for example, dim wocurrent as workorder ), because collection objects store items in variants. The object reference in variants is always bound at the end.
For many general program design tasks, the set object is also a useful optional solution for arrays. See "replacing arrays with Collections" in "programming again ".
Visual Basic provides many built-in collections. For comparison between them and collection objects, see collections in Visual Basic ".

Create your own collection class

Generally, you can use a set to implement object inclusion. The employees set of smallbusiness objects discussed in "Object Model" is used as an example. To implement this set, you can do this:
In the smallbusiness class module, declare the employees variable as an as collection and make it public. This is the simplest solution

From: http://blog.sina.com.cn/s/blog_4b168e640100lbma.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.