设置从属记录的属性时如何从上级记录的字段中获取值 [英] How to get value from field of superior record when it is setting property of subordinate record

查看:54
本文介绍了设置从属记录的属性时如何从上级记录的字段中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的项目中,我们具有以下结构和变量:

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;     

每当发生SetSize过程

Whenever procedure SetSize occurs

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

我们需要检查当前TMain的物料字段中的值.(因为尺寸大于一定值时,有必要更改材质).

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).

推荐答案

您需要具有指向"main"(主)对象的指针.记录每个部分.您可以这样做:

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;

为此,您必须先分配TPart.Main属性,然后再使用它.您没有显示如何在应用程序中创建TPart记录.一种方法是在TMain中添加方法AddPart().然后在该方法内部,很容易将"Main"分配给"Main".属性.

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.

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

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.

这篇关于设置从属记录的属性时如何从上级记录的字段中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆