Polymorphic behavior in VB6

I recently noticed the CallByName keyword in VB6.

Since it takes an object, a procedure name, a "call type" and an array of arguments, can this be used to "fake" some types of polymorphic behavior?

I can make 2 classes, class A and B, each with the same Foo method, and do:

Dim list As New Collection Dim instanceA As New ClassA Dim instanceB As New ClassB Dim current As Object Call list.Add(instanceA) Call list.Add(instanceB) For Each current in list Call CallByName(current, "methodName", vbMethod) Next 

Has anyone done this before? Problems? A terrible idea or a brilliant idea? Effects? Unintended consequences?

+4
source share
3 answers

Why fake polymorphism? VB6 has real polymorphism in the form of interfaces:

 ' Interface1.cls ' Sub Foo() End Sub ' --------------------------------------------- ' ' Class1.cls ' Implements Interface1 Private Sub Interface1_Foo() ? "Hello from class 1" End Sub ' --------------------------------------------- ' ' Class2.cls ' Implements Interface1 Private Sub Interface1_Foo() ? "Hello from class 2" End Sub ' --------------------------------------------- ' ' Module1.mod ' Dim x As Interface1 Set x = New Class1 Call x.Foo() Set x = New Class2 Call x.Foo() 
+14
source

Although I agree with Mr. Unicorn, I cannot help but note that CallByName is also not necessary (in this case), because you can call the method using the standard method syntax, and this will lead to a late (i.e. not allowed at compile time):

 ... For Each current In list Call current.methodName Next 

The real use of CallByName is to refer to the names / properties of a method in which the name comes from a (possibly calculated) string value ... an absolute abomination, in my opinion.

+6
source

If you are in a situation where you have inherited a huge project that does not have a single interface (it looks like you did), then CallByName is a terrific tool for faking polymorphism. I use it all the time - there have never been any problems.

+2
source

Source: https://habr.com/ru/post/1306055/


All Articles