For programmers and programming enthusiasts, the technology of classes in VB is a difficult point in learning. In the development process of large-scale software, modules (Moudle), controls (Activeocx), link libraries (Activedll) and classes (Classmoudle) It constitutes a systematic and efficient software engineering, and class technology is the basis of control and link library technology. Therefore, it is very meaningful to master the theory and programming methods of classes.
(1) Basic definition and application overview of classes ;
A class is a high-level code module that contains methods, properties, and data members. It is not only within the scope of the module, but also an Activeocx without a graphical interface. Programmers can use it like a control, but they cannot see it. It is worth noting that classes cannot be inherited.
Classes enable us to efficiently complete complex operations on one or several specific objects. The actions of the object are the methods of the class, and the attributes of the object are the attribute processes of the class. Relatively speaking, if the object of programming is a group of things, then it is very appropriate for us to use standard modules. In the following two cases, classes should be used for code processing:
(1) Create a large number of objects with similar properties;
(2) Improve the encapsulation of code.
Creating a class is very simple. When writing code, select the "Add Class Module" item in the "Project" menu to add a blank class.
Class files are generally saved with a .cls extension.
(2) Implementation of class methods ;
The method of a class is similar to the interface function of a dynamic link library. It can accept specified type parameters from other form codes and pass them to the class. Generally speaking, class methods can specify whether there is a return value. It is usually a public procedure in the class. Consider the following code example, which causes a password box to reject non-letter input:
(1) cls-like code;
OptionExplicit' variable check
PRivateWithEventsmytxtAsTextBox
'The methods in this class accept and control a text password box
DimisNUMAsBoolean
'Module-level variables of the class
PublicSubAttach(itTEXTAsTextBox)
'Accept external variables into mytxt
Setmytxt=itTEXT
EndSub
PrivateSubmytxt_KeyUp(KeyCodeAsInteger,ShiftAsInteger)
isNUM=(KeyCode>=65)And(KeyCode<=90)
'Test whether the keyboard input in the password box is English letters
IfisNUM=FalseThen
Beep
mytxt.Text=
'If the input is not an English letter, the bell will ring and the contents of the password box will be cleared.
MsgBox illegal character input!
EndIf
Debug.Printmytxt.Text
'Debug output password box content
EndSub
'End of class code
(2) Class reference ;
The classes that have been written can be referenced in two formats. The first way: Private (public or dim) myCLS (specified class name) AsNewcls (the written class name); the second way is more suitable for programming style. Older programmers: first make a module-level declaration - DimmyCLSAscls - in the form code, and then make a specific definition - Setmycls=Newcls in the specific code process. There may be differences in the efficiency and simplicity of the code between these two methods, but in the author's programming practice, there is no special feeling. However, I prefer the first method because it is more convenient to write. In addition, at the end of the code, it is a very good programming habit to use SetmyCLS=Nothing to cancel the resource occupation of the class.
In the form form1 (the form has a password box control text1, passworldchar=*) add the following code:
OptionExplicit
PrivatemyCLSAsNewcls
'Quote cls
PrivateSubForm_Load()
myCLS.AttachText1
'Startup class
EndSub
'Remember to release resources at the end of the code
PrivateSubForm_Unload(CancelAsInteger)
SetmyCLS=Nothing
End
EndSub
The code in this article shows the code writing process and calling method of the class method (although it is very similar to the event of the class). Its effect is that if a non-letter is entered in the password box, the system will ring and the password box will be deleted. of the original data - protecting the password to a certain extent.
A class method does not require any parameters, which is similar to a public function or procedure. It is also the most widely used in classes. In the next article I will discuss how to use the properties, events, and methods of classes for comprehensive programming.
We discussed the theory of classes, the creation of classes, and the programming practice of class methods. In fact, the main reason why classes can be widely used in software engineering is that they can very conveniently encapsulate many attributes needed for programming. This It not only enables programmers to overcome the complexity in the design and debugging of controls (ocx) and link libraries (dll) to a certain extent, but also improves the simplicity and efficiency of program codes - this article will discuss complete class programming, including methods , attributes and basic events.
(1) Characteristics and definitions of class attributes;
Similar to the properties of standard controls, class properties allow the user to assign values within a specified data range, and these values are shared by various parts of the code within the class. The acquisition and transfer of properties require programming through the PropertyLet and PropertyGet statements. Of course, we first need to define the corresponding variables at the global or module level in the class.
(2) Attributes and basic definitions of events;
Similar to the events of the form, classes also have two basic events, Class_Initialize (triggered when the class is loaded) and Class_Terminate (triggered when the class is unloaded), both of which are private. In fact, we can completely ignore these two events - as long as you remember to complete the methods and properties of the class.
Classes can also define their own events, which are similar to the programming format of methods, except that the WithEvents keyword is required for parameter declaration, and the event cannot have any named parameters or optional parameters, and it has no return value.
In fact, well-structured methods and properties can completely replace the events of complex-structured classes.
(3) Programming examples of class methods, events and properties;
The purpose of this program is to control all uppercase, lowercase and reverse sorting of the contents of the text box in the form through classes.
In order to facilitate the writing and calling of code, I referenced the enumeration programming method in the class.
The following code is in class Class1:
OptionExplicit
PrivateWithEventsmyTXTAsTextBox
'Method parameter interface
PublicEnumsTYLE
Lcaseit' lowercase attribute
Lbigit' capitalization attribute
Nlogoit' reverse sort attribute
EndEnum
'Custom enumeration, used to implement automatic assignment of attributes
PrivatemvarBiaozhiAssTYLE
'Implement the connection of enumeration constants
PublicFunctiondONE()AsString'
'DONE method is used to set the
'Perform corresponding character conversion operations in the form text box
'And return the converted string
IfmvarBiaozhi=NlogoitThen
dONE=StrReverse(myTXT)
'Reverse sort
ElseIfmvarBiaozhi=LcaseitThen
dONE=LCase(myTXT)
'Force lowercase conversion
Else
dONE=UCase(myTXT)
'Force uppercase conversion
EndIf
EndFunction
'DONE method ends
PublicPropertyLetBiaozhi(ByValvDataAssTYLE)
'Get the assigned value of the attribute
mvarBiaozhi=vData
EndProperty
PublicPropertyGetBiaozhi()AssTYLE
'Transfer attribute values to the class
SetBiaozhi=mvarBiaozhi
EndProperty
PublicSubAttach(itTEXTAsTextBox)
'Method of connection class
SetmyTXT=itTEXT
EndSub
PrivateSubClass_Initialize()
'This event is activated when the class is loaded
MsgBox Hello! This program shows you the techniques of programming using class methods, properties, and events!
EndSub
PrivateSubClass_Terminate()
'This event is activated when the class is unloaded
MsgBox Hello! Remember to fill in the code after the object is revoked in Class_Terminate!
EndSub
'The code of the class is all over
(4) Reference programming of form code;
Add text control TEXT1, drop-down list control COMBO1, and command button COMMAND1 (CAPTION=Start conversion) to form FORM1, and adjust the three controls to the appropriate positions.
DimmyTAsNewClass1
'Class reference
PrivateSubForm_Load()
Combo1.Clear
Combo1.AddItem string uppercase conversion
Combo1.AddItem string lowercase conversion
Combo1.AddItem string reverse sorting
Combo1.ListIndex=0
'Add attribute options to the list box
EndSub
PrivateSubCommand1_Click()
'Activate the class when the command button is pressed
myT.AttachText1
'Method parameter connection
SelectCaseCombo1.ListIndex
Case0
myT.Biaozhi=Lbigit
Case1
myT.Biaozhi=Lcaseit
Case2
myT.Biaozhi=Nlogoit
EndSelect
'According to the selection in the list box, assign a value to the Biaozhi attribute of the class
'Note that in the programming environment, the above attribute values are automatically added
Text1.Text=myT.dONE
'Return the string after sorting
EndSub
PrivateSubForm_Unload(CancelAsInteger)
SetmyT=Nothing
End
'Good programming habits
EndSub
How about, our code looks so concise, it feels like using a control, which can not only be called at will, but also conveniently use the automatic prompt function of VB.
(5) Summary of class programming techniques;
Strictly speaking, classes are a very useful technology in VB programming, and they are also difficult to learn and master. Classes are widely and effectively used in large-scale software projects. However, in small-scale software development, in order to improve software For efficiency and code clarity, you should avoid using more class modules, controls and connection libraries and replace them with standard modules.
The code example in this article is relatively simple, but it covers all aspects of module programming technology. I hope beginners can learn from it and programmers can discuss it together. We should believe that no matter how complex the high-rise buildings are, they are all made of ordinary bricks. Similarly, no matter how complex the software projects are, they are composed of basic program statements. Programming enthusiasts and programmers The only difference from the analyst is that the programs constructed with the same program statements are different. ->