How to get value from field of superior record when it is setting property of subordinate record

Viewed 57

In our project we have these structures and variable:

  TPart = record
  private
    ...
    FSize: Integer;
    procedure SetSize(const Value: Integer);
  public
    ...
    property Size : Integer read FSize write SetSize;
  end;

  TMain = record
    ...
    material : Byte;
    parts : array [1..10] of TPart;
  end;

  TAMain = array [1..200] of TMain;

var     
  whole : TAMain;

procedure TPart.SetSize(const Value: Integer);
begin
  FSize := Value;
  // need to know material current TMain
end;     

Whenever procedure SetSize occurs

whole[x].parts[y].Size := ...;

we need to check value in material field of current TMain. (Because when the size is bigger than certain value, it is necessary to change material).

1 Answers

You need to have a pointer to the "main" record for each part. You can do it like this:

type
  PMain = ^TMain;

  TPart = record
  private
    //...
    FSize : Integer;
    FMain : PMain;
    procedure SetSize(const Value: Integer);
  public
    //...
    property Size : Integer read FSize write SetSize;
    property Main : PMain   read FMain write FMain;
  end;

  TMain = record
    //...
    material : Byte;
    parts    : array [1..10] of TPart;
  end;

  TAMain = array [1..200] of TMain;


procedure TPart.SetSize(const Value: Integer);
begin
  FSize := Value;
  // need to know material current TMain
  if not Assigned(FMain) then
      raise Exception.Create('Main not assigned for that part');

  if FMain.material = 123 then begin
      // Do something
  end;
end;

For this to work, you have to assign TPart.Main property before it is needed. You didn't show how TPart records are created in your application. One way to do it is to add a method AddPart() in TMain. Then inside that method, it is easy to assign the "Main" property in the added part.

And by the way, using records is probably not the best design for this. Using classes as suggested Andreas Rejbrand if probably a better idea. The code is almost the same except there is no more explicit pointer. Just a reference to the main instance.

Related