Thema: Records

Einzelnen Beitrag anzeigen

mytbo

Registriert seit: 8. Jan 2007
472 Beiträge
 
#25

AW: Records

  Alt 6. Nov 2023, 22:10
Code:
Procedure Test;
var
  MyRec: TMyRecord; Init;
and that it, also we can have a directive to tell the compiler to handle every record forward in this unit to Init to default, here comes simple initialization like filling with 0 or calling TMyRecord.Init;
In newer Delphi versions you can already do a lot. Defined with a few lines and clearer for me:
Delphi-Quellcode:
type
  TTestRec = record
    Name: String;
    Count: Integer;
    Address: array of record
      Street: String;
      ZIPCode: Integer;
    end;
  public
    function AddAddress(const pmcStreet: String; pmZIPCode: Integer): Integer;
    procedure Init;
    procedure Clear;
  end;

function TTestRec.AddAddress(const pmcStreet: String; pmZIPCode: Integer): Integer;
begin
  Result := Length(Address);
  SetLength(Address, Result + 1);
  with Address[Result] do
  begin
    Street := pmcStreet;
    ZIPCode := pmZIPCode;
  end;
end;

procedure TTestRec.Init;
begin
  FillChar(Self, SizeOf(Self), 0);
end;

procedure TTestRec.Clear;
begin
  Finalize(Self);
  Init;
end;
Or functions are outsourced to a record helper. Use it like this:
Delphi-Quellcode:
var
  rec: TTestRec;
begin
  rec.Init;
  ShowMessage(rec.Count.ToString);
  rec.AddAddress('Paddington', 123);
  ShowMessage(rec.Address[0].ZIPCode.ToString);
  rec.Clear;
  ShowMessage(Length(rec.Address).ToString);
Zitat von Kas Ob.:
... No .Free and definitely no that ugly nested try..finally, ...
There is something similar (not the same) in mORMot. Used very carefully, it can be helpful:
Delphi-Quellcode:
var
  sList1, sList2: TStringList;
  oList1, oList2: TObjectList;
begin
  with TAutoFree.One(sList1, TStringList.Create) do
  begin
    sList1.Add('Test');
    Another(oList1, TObjectList.Create);
    oList1.Add(TObject.Create);
  end;

  with TAutoFree.Several([
    @sList2, TStringList.Create,
    @oList2, TObjectList.Create]) do
  begin
    sList2.Add('Test');
    oList2.Add(TObject.Create);
  end;
end;
I would like to see the NameOf function much more urgently. Although it is highly voted, we hear nothing about its realization.

With best regards
Thomas
  Mit Zitat antworten Zitat