trenchmouth wrote:
Does anybody know how I can loop through all the properties in a class I
have created? Can I use Me to refer to the properties? I'm using VB6.
Many thanks.
That is a simple question with a long answer. First, why would you even
want that?
If you just want access to a property, call it by its name (better said,
the name of its accessor (=function or property get)).
If you really want to loop through them in your code, consider the
following lines of thought.
If your object has looping in its nature (like a collection class, for
example), treat it like a collection and provide some "Item" accessor
that takes both names and numbers. If you make it the default method,
you can use the bang operator instead of the quoted notation
(Forms.Controls!cmdButton instead of Forms.Controls("cmdButton") ).
If your object has looping in its nature, why not ask the object ITSELF
do do the looping? You then create some sort of equivalent to a control
array, where events just pass the number of the specific control that
really generated the event. So, suppose your collection needs to save
all its members to a file, you just can can create a SaveAllMembersTo
method that takes a file or a stream object as a parameter.
Now if you are trying to do something like XML serialization in .NET,
where code is generated for each public (!) variable in a class for
webclasses, you will need reflection.
Reflection is a set of methods to query the interface of an object. So
you can ask questions like "does this object also implements this
interface?" or "Does this object have this method?" or "What is the base
class name of this object?"
If you want my advice: DON'T! All these questions arise from
object-oriented design errors and can be better (clearer and better to
maintain) solved by applying the right design. If you really want to use
reflection, beware that your classes might not be called directly
anymore and will therefore be optimised out of your compiled
application. You will have to change your project settings to avoid
this. There is a reflection package for Visual Basic, if you want. Just
google for it.
Better desing options are:
"does this object also implements this interface?"
Know what objects you have. If they come out of a collection class,
make sure the collection only accepts objects of a certain type. If some
subtypes must do things and others don't, an empty implementation of an
interface method is still better than using reflection.
"Does this object have this method?"
Make the object implement an interface and solve the class-specific
actions in its implementation.
"What is the base class name of this object?"
Strange question. Subclasses should always be able to be substituted
for their superclasses. If not, it is not really a subclass.
I hope I did not drown you in information.
Best regards.