Alright, so I have a base class which we’ll call TFruit. From this there are various descendants like TApple, TOrange and so on. I need to save the properties of the descendant classes to a file.
In order to be able to create the right class when loading the data, each class needs to have an ID that I write to the file before writing the actual data. Currently, I’ve come up with the following way of doing it:
type
TFruit = class
const ID = 0;
end;
TApple = class(TFruit)
const ID = 1;
end;
TOrange = class(TFruit)
const ID = 2;
end;
Testing this, I found out that I need to be super careful which class I declare. If I use this:
var Fruit: TFruit;
Fruit := TOrange.Create;
…then Fruit.ID will return zero. However, declaring Fruit as a TOrange will yield the expected result Fruit.ID = 2 (anyone know why?)
So basically, am I doing this right or is there a better way to do it? Having to create a class function and return a value from there seems very ugly by comparison (extra function declaration, implementation and code).
An easier to maintain solution would be to create a mapping class where you register all classes you’d like to convert to an integer.
Advantages
Usage
Implementation
Please note that there are better structures to map a String to an Integer. Writing this without a compiler and don’t knowing many basic structures beyond Delphi5, I’ve chosen an obvious implementation.
Note that the IsAlreadyRegistered overloaded functions still have to be written