delphi - 设置下级记录属性时如何从上级记录字段中获取值
问题描述
在我们的项目中,我们有这些结构和变量:
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 的材料字段中的值。(因为当尺寸大于一定值时,需要更换材料)。
解决方案
您需要有一个指向每个部分的“主要”记录的指针。你可以这样做:
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 的建议使用课程。除了没有更显式的指针外,代码几乎相同。只是对主实例的引用。
推荐阅读
- java - 如何更新二维数组代码中蛇和梯子的位置?
- java - 引起:io.grpc.StatusRuntimeException:内部:HTTP/2 错误代码:PROTOCOL_ERROR
- excel - MS Excel 的乘法助手 Visual Basic
- javascript - Js 类名不适用于 fetch json
- html - 尽管客户端工作 100% 正常,但在上传到主机服务器后部分网站损坏
- javascript - 从联合中删除类型或在 array.filter 中使用空联合
- python-3.x - 如何抑制或防止从 Box python API 返回的 http 标头响应在 Jupyter 笔记本的单元格输出中打印
- javascript - 如何在图表上显示不同的工具提示(在列中)?
- scala - 播放 json 的 Intellij Scala 编译问题
- java - Lombok @Builder无法解析方法'builder'