开发者

Multiple constructors in VB6?

开发者 https://www.devze.com 2023-02-17 19:40 出处:网络
Is it possible to have multiple constructors in vb6?The reason I\'m asking is because I see the class initialize, but i don\'t know if I can stick in 0 or more parameters into a constructor or if clas

Is it possible to have multiple constructors in vb6? The reason I'm asking is because I see the class initialize, but i don't know if I can stick in 0 or more parameters into a constructor or if class_initialize is the constructor and it can accept any number of parameters. Its confusing mainly because I am so familiar with开发者_运维知识库 c#, that going to vb6 is confounding as far as classes are concerned.


Class_Initialize is an event that gets always gets invoked as soon as an instance of the class is instantiated. It's not really comparable to a C# constructor.

For example, notice the Class_Initialize is created as Private, whereas a C# class with a private constructor cannot be instantiated.

While you can change a VB6 Class_Initialize event from Private to Public there wouldn't be much point: because the event is invoked on instantiation anyway, why would you want to call it explicitly a second time? (If you did, it would be better to have a public method that is called from the Class_Initialize event.)

You cannot add parameters to VB6 Class_Initialize event, not even Optional ones. Attempting to do so will cause a compile error.

The best you can do is to roll your own Initialize method, with parameter as required, which must be explicitly called, perhaps and have an internal flag isInitialized state variable to ensure the class is not used until the Initialize method has been invoked. Also consider a 'factory' approach: classes that are PublicNotCreatable with Friend Initialize methods invoked by the factory and served out to callers suitable initialized.


In VB6 you can specify method parameters as being optional. This means that you don't have to specify them when calling a function. In the case that they are not specified, a default value is given in the method signature.

An example from here:

Private Sub Draw(Optional X As Single = 720, Optional Y As Single = 2880)
    Cls
    Circle (X, Y), 700
End Sub

This can be called either:

Draw 'OR
Draw 100 'OR
Draw 200, 200

Edit
You can even use optional and regular parameters together, though I think you might have to put the optional ones at the end.

0

精彩评论

暂无评论...
验证码 换一张
取 消