views:

133

answers:

3

I'd like to compare the "state" of two components, say Comp1: TSomeComponent and Comp2: TSomeComponent, i.e. I want to compare the values of all the published properties of the two components. Some of the properties are indexed, like the TListBox.Items property. Is there an easy way to do this? Do I have to invoke some iterating RTTI code?

A: 

Unfortunately, there's no simple compare function in Delphi as far as I know. (I've stopped at D2007.) You could add a method "Compare" to the base class and build the comparison of all fields inside this method. (It should accept one parameter of the same base class.) With D2007 you could build this as a helper class, but you still need to specify the fields. Other classes could be inherited from this base class and override the base Compare method.

The use of RTTI will make it easier to compare fields of classes from different types but it's complex and error-prone. It will require a lot of testing with all kinds of different classes.

Workshop Alex
+2  A: 

An easy way would be to serialize them both with WriteComponent and compare the resulting strings. Note, however, that this would compare only published, not public, properties. But that is what you say you need, so...

Note that this would make, say, the order of the indexed properties significant. That may or may not be what you want.

Craig Stuntz
Thanks Craig, I was actually considering that. What I didn't write in my original question was that I wanted to compare the properties before I (in the case of differences) wrote the properties using WriteComponent. AFAIU you can't single out certain properties to be written using WriteComponent. Is this true? (For the moment, all I care about are the published props...)
conciliator
I believe you're right.
Craig Stuntz
Actually, you can fiddle what properties get written. Take a look at `TComponent.DefineProperties` and related methods/components. This was many years ago, but I've both suppressed properties and added properties not declared as published.
Craig Young
Craig, you can do that within the component, but not from the code calling the serialization.
Craig Stuntz
@Craig: Correct; one would have to modify/subclass the components to do this, but it can be done ;) Although, that said; it's a bad reason to subclass a component. So if the requirement is to compare only specific published properties, then RTTI is probably the best way to go.
Craig Young
A: 

A trick I use (but I would like to have something like this integrated in the IDE) is to copy the dfm part related to the 2 components (using ALT+F12) to access dfm and then I paste the 2 components in NotePad++ and I use the Compare Plugin to compare the 2. It gives a nice visual output, but this takes more time than selecting more components in the IDE (even from different windows) and then Compare them with a compare tool built in in the IDE.