Recent

Author Topic: [Solved] Looping over classes  (Read 1984 times)

MountainQ

  • Jr. Member
  • **
  • Posts: 65
[Solved] Looping over classes
« on: July 20, 2017, 11:27:44 am »
Hi folks,
I just bumped into the following problem:
Assume I have several child classes derived from a parent class; in my case reading information from different file types. In particular each child class can check whether the provided file content is valid. So in order to recognize an unknown file I have to check whether a class can successfully identify it; something like:
Code: Pascal  [Select][+][-]
  1. var
  2.   file: TParentFiletype;
  3.  
  4. file := TFileType1.Create(filename);
  5. if file.valid then Exit;
  6. file.Free;
  7. file := TFileType2.Create(filename);
  8.  
Is there a possibility to loop over the different child classes (not instances as of yet); if I write
Code: Pascal  [Select][+][-]
  1. var
  2.    files: array[0..1] of TParentFileType = (TFileType1, TFileType2);
  3.  
I get the error message
Quote
Error: typed constants of classes or interfaces are not allowed
I still assume, similar constructs/problems should be out there; however I could not find a solution.
As always: sorry to bother in case this is a trivial problem.
Thanks in advance
« Last Edit: July 20, 2017, 01:15:34 pm by MountainQ »

Martin_fr

  • Administrator
  • Hero Member
  • *
  • Posts: 9754
  • Debugger - SynEdit - and more
    • wiki
Re: Looping over classes
« Reply #1 on: July 20, 2017, 12:25:44 pm »
Code: Pascal  [Select][+][-]
  1. type
  2.   TParentFileTypeClass = class of TParentFileType;
  3. var
  4.    files: array[0..1] of TParentFileTypeClass = (TFileType1, TFileType1);

Make sure that any method you call on the class is virtual/overwritten!

Code: Pascal  [Select][+][-]
  1.    TParentFileType= class
  2.       constructor Create; virtual;
  3.       class procedure CheckFile; virtual;
  4.    end;
  5.  
and overwrite in the child classes
« Last Edit: July 20, 2017, 12:28:27 pm by Martin_fr »

MountainQ

  • Jr. Member
  • **
  • Posts: 65
Re: Looping over classes
« Reply #2 on: July 20, 2017, 12:37:03 pm »
@Martin_fr: Thank you so much; using the concept of class references is exactly what I was looking for.
Thanks one more time; this solves the issue and topic.

 

TinyPortal © 2005-2018