设置下级记录属性时,如何从上级记录的字段中获取值
How to get value from field of superior record when it is setting property of subordinate record
在我们的项目中,我们有这些结构和变量:
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 的 material 字段中的值。 (因为当尺寸大于一定值时,需要改变material)。
您需要有一个指向每个部分的“主”记录的指针。你可以这样做:
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 的建议使用 类。除了没有更明确的指针外,代码几乎相同。只是对主实例的引用。
在我们的项目中,我们有这些结构和变量:
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 的 material 字段中的值。 (因为当尺寸大于一定值时,需要改变material)。
您需要有一个指向每个部分的“主”记录的指针。你可以这样做:
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 的建议使用 类。除了没有更明确的指针外,代码几乎相同。只是对主实例的引用。