首页 > 解决方案 > 设置下级记录属性时如何从上级记录字段中获取值

问题描述

在我们的项目中,我们有这些结构和变量:

  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;     

每当过程 SetSize 发生时

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

我们需要检查当前 TMain 的材料字段中的值。(因为当尺寸大于一定值时,需要更换材料)。

标签: delphi

解决方案


您需要有一个指向每个部分的“主要”记录的指针。你可以这样做:

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;

为此,您必须在需要之前分配 TPart.Main 属性。您没有展示如何在您的应用程序中创建 TPart 记录。一种方法是在 TMain 中添加方法 AddPart()。然后在该方法中,很容易在添加的部分中分配“Main”属性。

顺便说一句,使用记录可能不是最好的设计。如果可能是一个更好的主意,请按照 Andreas Rejbrand 的建议使用课程。除了没有更显式的指针外,代码几乎相同。只是对主实例的引用。


推荐阅读