I'm using Delphi 2007 to maintain an old project, I have a problem accessing class constants from a Class Reference variable, I get always the parent class constant instead of the children one.
Suppose to have a parent class, some child classes, a class reference and finally a const array to store the class references for looping purposes.
take a look at following simple program:
program TestClassConst;
{$APPTYPE CONSOLE}
uses
SysUtils;
type
TParent = class
const
ClassConst = 'BASE CLASS';
end;
TChild1 = class(TParent)
const
ClassConst = 'CHILD 1';
end;
TChild2 = class(TParent)
const
ClassConst = 'CHILD 2';
end;
TParentClass = class of TParent;
TChildClasses = array[0..1] of TParentClass;
const
ChildClasses: TChildClasses = (TChild1, TChild2);
var
i: integer;
c: TParentClass;
s: string;
begin
try
writeln;
writeln('looping through class reference array');
for i := low(ChildClasses) to high(ChildClasses) do begin
c := ChildClasses[i];
writeln(c.ClassName, ' -> ', c.ClassConst);
end;
writeln;
writeln('accessing classes directly');
writeln(TChild1.ClassName, ' -> ', TChild1.ClassConst);
writeln(TChild2.ClassName, ' -> ', TChild2.ClassConst);
except
on E: Exception do
Writeln(E.Classname, ': ', E.Message);
end;
end.
When it runs I get:
looping through class reference array
TChild1 -> BASE CLASS
TChild2 -> BASE CLASS
accessing classes directly
TChild1 -> CHILD 1
TChild2 -> CHILD 2
I expected to see 'CHILD 1' and 'CHILD 2' also in array loop!
Can anyone explain me why it does not work with class reference?