重拾VB614:Adding Properties, Methods and Events to a Class

来自MSDN-2001-OCT: Visual Tools and Languages/Visual Studio 6.0 Documentation/Visual Basic Documentation/Using Visual Basic/Programmer’s Guide/Part 2: What Can You Do With Visual Basic/Programming with Objects/Adding Properties and Methods to a Class及之后的章节

1. Property Procedures

(1) Note Don't implement a property as a public variable just to avoid the overhead of a function call. Behind the scenes,Visual Basic will implement the public variables in your class modules as pairs of property procedures anyway,because this is required by the type library.

(2) 一般来说,如果属性的取值没有特殊要求,也不会引起对象内部状态和其他属性的连锁变化的话,就可以用Public变量取代property。

(3) Property procedures are public by default,so if you omit the Public keyword,they will still be public.

(4) Arguments of Paired Property Procedures Must Match. When you use multiple arguments,the arguments of a pair of property procedures must match.

The data type of the Property Get procedure must be the same as the data type of the last argument (n+1) in the related Property Let or Property Set.

The data type of the final argument in a Property Set declaration must be either an object type or a Variant.

The most common use for property procedures with multiple arguments is to create property arrays.

(5) Variant Properties: Read-write properties of the Variant data type are the most complicated. They use all three property procedure types,as shown here:

Private mvntAnything As Variant

Public Property Get Anything() As Variant
' The Set statement is used only when the Anything
' property contains an object reference.
If IsObject( mvntAnything) Then
Set Anything = mvntAnything
Else
Anything = mvntAnything
End If
End Property

Public Property Let Anything( ByVal NewValue As Variant)
' (Validation code omitted.)
mvntAnything = NewWidget
End Property

Public Property Set Anything( ByVal NewValue As Variant)
' (Validation code omitted.)
Set mvntAnything = NewWidget
End Property

(6) Write-Once Properties:

' Private data storage for Parent property.
Private mdeptParent As Department

Property Get Parent() As Department
' Use the Set statement for object references.
Set Parent = mdeptParent
End Property

' The property value can only be set once.
Public Property Set Parent( ByVal NewParent _
As Department)
If deptParent Is Nothing Then
' Assign the initial value.
Set mdeptParent = NewParent
Else
Err . Raise Number : = vbObjectError + 32144 , _
Description : = "Parent property is read-only"
End If
End Property

2. Method

(1) Since Sub and Function procedures are public by default,you don't even have to explicitly specify the Public keyword to create a method.

(2) Is It a Property or a Method?

a) If you want people to think of it as data about the object,make it a property. If you want them to think of it as something the object does,make it a method.

b) will the user of a Widgets collection be allowed to code the following?

Set Widgets.Item(4) = wdgMyNewWidget

If so,implement the member as a read-write property,using Property Get and Property Set,because methods don't support this syntax.

c) You can also suppose for a moment that your object is like a control. Can you imagine the member showing up in the Property window,or on a property page? If that doesn't make sense,don't implement the member as a property.

d) The Sensible Error Argument: If you forget that you made Item a read-only property and try to assign a value to it,you'll most likely find it easier to understand the error message Visual Basic raises for a Property Get — "Can't assign to read-only property" — than the error message it raises for a Function procedure — "Function call on left-hand side of assignment must return Variant or Object."

3. Making a Property or Method the Default

(1) To set a property or method as the default,On theTools menu,select Procedure Attributes to open the Procedure Attributes dialog box. Click Advanced to expand the Procedure Attributes dialog box. You can also open the Procedure Attributes dialog box from the Object Browser.

(2) Important A class can have only one default member. If a property or method is already marked as the default,you must reset its procedure ID to None before making another property or method the default. No compile errors will occur if two members are marked as default,but there is no way to predict which one Visual Basic will pick as the default.

(3) The Procedure Attributes dialog box only allows you to select public properties and methods as the default for a class. If you make a public property or method the default for a class,and later change the declaration to Private or Friend,the property or method may continue to behave as if it were still declared Public.

To correct this problem,you must make the property or method Public again,because the Procedure Attributes dialog box will not show procedures declared Private and Friend. Once you have changed the declaration to Public,you can use the Procedure Attributes dialog to remove the Default attribute. You can then change the declaration back to Friend or Private.

4. Friend Properties and Methods

(1) Friend members look just like Public members to other objects in your project. That is,they appear to be part of a class's interface. They are not.

(2) In the ActiveX components,Friend members play an important role. Because they're not part of an object's interface,they can't be accessed by programs that use the component's objects. They're visible to all the other objects within the component,however,so they allow safe internal communication within the component.

(3) Important Because Friend members aren't part of an object's public interface,they can't be accessed late bound — that is,through variables declared As Object. To use Friend members,you must declare variables with early binding — that is,As classname.

(4) Standard Exe projects can't be ActiveX components,because their class modules can't be Public,and thus can't be used by other applications. All communication between objects in a Standard Exe project is therefore private,and there's no need for Friend members.

(5) However,Friend members have one particularly useful feature. Because they're not part of an ActiveX interface,they can be used to pass user-defined types between objects without exposing them publicly. For example,suppose you have the following user-defined type in a standard module:

Public Type udtDemo
intA As Integer
lngB As Long
strC As String
End Type

You can define the following private variable and Friend members in Class1:

Private mDemo As udtDemo

Friend Property Get Demo() As udtDemo
Demo = mDemo
End Property

' Note that udtDemo must be passed by reference.
Friend Property Let Demo( NewDemo As udtDemo)
mDemo = NewDemo
End Property

Friend Sub SetDemoParts( ByVal A As Integer , _
ByVal B As Long , ByVal C As String)
mDemo . intA = A
mDemo . lngB = B
mDemo . strC = C
End Sub

Public Sub ShowDemo()
MsgBox mDemo . intA & vbCrLf _
& mDemo . lngB & vbCrLf & mDemo . strC
End Sub

You can then write the following code to use Class1 :

Private Sub Command1_Click()
Dim c1A As New Class1
Dim c1B As New Class1
c1A . SetDemoParts 42 , 1138 , "Howdy"
c1B . Demo = c1A . Demo
c1B . ShowDemo
End Sub

The message box will display 42,1138,and "Howdy."

5. Adding Events to a Class

(1) Properties and methods are said to belong to incoming interfaces,because they're invoked from outside the object. By contrast,events are called outgoing interfaces,because they're initiated within the object,and handled elsewhere.

(2) Events are outgoing interfaces (that is,interfaces that reach out and touch other objects),while properties and methods belong to incoming interfaces (that is,interfaces whose members are invoked by other objects). The default interface of a Visual Basic object is an incoming interface.

(3) Note Events cannot have named arguments,optional arguments,or ParamArray arguments. Events do not have return values. Events are always Public.

(4) An object that raises events is called an event source. To handle the events raised by an event source,you can declare a variable of the object's class using the WithEvents keyword.

(5) WithEvents variables must be module-level variables.

  • A WithEvents variable cannot be a generic object variable. That is,you cannot declare it As Object — you must specify the class name when you declare the variable.
  • You cannot declare a WithEvents variable As New. The event source object must be explicitly created and assigned to the WithEvents variable.
  • You cannot declare WithEvents variables in a standard module. You can declare them only in class modules,form modules,and other modules that define classes.
  • You cannot create arrays of WithEvents variables.
  • 6. Comparing WithEvents to Control Events on Forms

    A control is treated as a property of the form class,and the name of that property is the value you assigned to the control's Name property in the Properties window.

    It's as if there's a Public module-level variable with the same name as the control,and all of the control's event procedure names begin with that variable name,just as they would with a WithEvents variable.

    The difference between the two cases is that Visual Basic automatically creates instances of all the controls on a form when the form is created,whereas you have to create your own instances of classes whose events you want to handle,and assign references to those objects to WithEvents variables.

    相关文章

    Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
    VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
    在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
    转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
    Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
      窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...