Question

Hello I have a question is possible I do a loop for create subclass in Delphi? I saw some about RTTI but I can't found how create a class in property in run time

exemple

thank you

Type
  TclassX = class
  private
  public
     X1 : integer;
     X2 : String;
end;

Type

  TRecord = class
     ID : TClassX;
     NAME : TClassX;
  private
  public
     contructor Create();
     property ID : TClassX read FY1 write SetY1;
     property NAME : TClassX read FY2 write SetY2;
end;

implementation

constructor TRecord.Create;
begin
   ///HERE I WHANT MAKE A LOOP AND DON'T MAKE ONE BY ONE
   // property[0] := ID;
   // property[1] := NAME;
   // FOR I:= 0 TO 1 DO BEGIN
   // ***PROPERTY[i] := TClassX.Create; ---*** not correct just exemple
   // END; 

   ID := TClassY.Create;  
   NAME := TClassY.Create;  
end;
Was it helpful?

Solution

I would store the class references in an array. And then for syntactical ease, use an indexed property:

type
  TMyClass = class
  private
    FY: array [1..2] of TClassX;
    function GetY(Index: Integer): TClassX;
    procedure SetY(Index: Integer; const Value: TClassX);
  public
    constructor Create;
    property Y1: TClassX index 1 read GetY write SetY;
    property Y2: TClassX index 2 read GetY write SetY;
  end;

function TMyClass.GetY(Index: Integer): TClassX;
begin
  Result := FY[Index];
end;

procedure TMyClass.SetY(Index: Integer; const Value: TClassX);
begin
  FY[Index] := Value;
end;

Then you can simply loop over FY to instantiate the objects.

constructor TMyClass.Create;
var
  i: Integer;
begin
  inherited;
  for i := low(FY) to high(FY) do begin
    FY[i] := TClassY.Create;
  end;
end;

Having said all that, is all of this scaffolding really necessary. Would it not just be easier to use an array property?

type
  TMyClass = class
  private
    FY: array [1..2] of TClassX;
    function GetY(Index: Integer): TClassX;
    procedure SetY(Index: Integer; const Value: TClassX);
  public
    constructor Create;
    property Y[Index: Integer]: TClassX read GetY write SetY;
  end;

Then, instead of writing Y1 you write Y[1]. Using array properties gives you so much more flexibility because you can index them with variables and so decide at runtime rather than compile time which object you are referring to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top