Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a record be used as a property of an object?

I'd like to make a record as an object's property. The problem is that when I change one of the fields of this record, the object isn't aware of the change.

type
  TMyRecord = record
    SomeField: Integer;
  end;

  TMyObject = class(TObject)
  private
    FSomeRecord: TMyRecord;
    procedure SetSomeRecord(const Value: TMyRecord);
  public
    property SomeRecord: TMyRecord read FSomeRecord write SetSomeRecord;
  end;

And then if I do...

MyObject.SomeRecord.SomeField:= 5;

...will not work.

So how do I make the property setting procedure 'catch' when one of the record's fields is written to? Perhaps some trick in how to declare the record?

More Info

My goal is to avoid having to create a TObject or TPersistent with an OnChange event (such as the TFont or TStringList). I'm more than familiar with using objects for this, but in an attempt to cleanup my code a little, I'm seeing if I can use a Record instead. I just need to make sure my record property setter can be called properly when I set one of the record's fields.

like image 914
Jerry Dodge Avatar asked Feb 06 '12 06:02

Jerry Dodge


1 Answers

How about using a TObject instead of a Record?

type
  TMyProperties = class(TObject)
    SomeField: Integer;
  end;

  TMyObject = class(TObject)
  private
    FMyProperties: TMyProperties;     
  public
    constructor Create;
    destructor Destroy; override;

    property MyProperties: TMyRecord read FMyProperties;
  end;

implementation

constructor TMyObject.Create;
begin
  FMyProperties := TMyProperties.Create;
end;

destructor TMyObject.Destroy;
begin
  FMyProperties.Free;
end;

You can now read and set the properties of TMyProperties like this:

MyObject.MyProperties.SomeField := 1;
x := MyObject.MyProperties.SomeField;

Using this method, you don't need to individually get/set the values to/from the record. If you need to catch changes in FMyProperties, you can add a 'set' procedure in the property declaration.

like image 82
norgepaul Avatar answered Sep 19 '22 16:09

norgepaul