Einzelnen Beitrag anzeigen

Benutzerbild von KodeZwerg
KodeZwerg

Registriert seit: 1. Feb 2018
3.691 Beiträge
 
Delphi 11 Alexandria
 
#2

AW: Die Arbeit mit Fake-Objekten erspart die Prüfung auf Nil

  Alt 24. Jun 2023, 11:14
Nur mal auf die schnelle zusammengebasteln wie ich es meist klassisch mache ...
Code:
type
  TPerson = packed record
    FirstName,
    SurName: string;
    Age: Integer;
  end;
  TPersons = array of TPerson;

type

  { TPersonalClass }

  TPersonalClass = class(TObject)
    strict private
      FPersons: TPersons;
      FCount: Integer;
      FIndex: Integer;
    private
      procedure SetIndex(const AIndex: Integer);
    public
      constructor Create;
      destructor Destroy; Override;
      procedure Add(const AFirstName, ASurName: string; const AAge: Integer); overload;
      procedure Add(const APerson: TPerson); overload;
      function GetPerson: TPerson;
      procedure SetPerson(AValue: TPerson);
    published
      property Index: Integer read FIndex write SetIndex;
      property Count: Integer read FCount;
  end;

{ TPersonalClass }

constructor TPersonalClass.Create;
begin
  FCount := 0;
  FIndex := -1;
  SetLength(FPersons, 0);
end;

destructor TPersonalClass.Destroy;
begin
  SetLength(FPersons, 0);
  inherited Destroy;
end;

procedure TPersonalClass.SetIndex(const AIndex: Integer);
begin
  if (AIndex < FCount) then
    FIndex := AIndex;
end;

procedure TPersonalClass.Add(const AFirstName , ASurName: string;
  const AAge: Integer);
var
  i: Integer;
begin
  if ((AFirstName <> '') and (ASurName <> '')) then
    begin
      i := Length(FPersons);
      SetLength(FPersons, Succ(i));
      FPersons[i].FirstName := AFirstName;
      FPersons[i].SurName := ASurName;
      FPersons[i].Age := AAge;
      FCount := Length(FPersons);
      if ((FIndex = -1) and (FCount > 0)) then
        FIndex := Pred(FCount);
    end;
end;

procedure TPersonalClass.Add(const APerson: TPerson);
var
  i: Integer;
begin
  if ((APerson.FirstName <> '') and (APerson.SurName <> '')) then
    begin
      i := Length(FPersons);
      SetLength(FPersons, Succ(i));
      FPersons[i].FirstName := APerson.FirstName;
      FPersons[i].SurName := APerson.SurName;
      FPersons[i].Age := APerson.Age;
      FCount := Length(FPersons);
      if ((FIndex = -1) and (FCount > 0)) then
        FIndex := Pred(FCount);
    end;
end;

function TPersonalClass.GetPerson: TPerson;
begin
  if (FIndex >= 0) then
    begin
      Result.FirstName := FPersons[FIndex].FirstName;
      Result.SurName := FPersons[FIndex].SurName;
      Result.Age := FPersons[FIndex].Age;
    end;
end;

procedure TPersonalClass.SetPerson(AValue: TPerson);
begin
  if (FIndex >= 0) then
    begin
      FPersons[FIndex].FirstName := AValue.FirstName;
      FPersons[FIndex].SurName := AValue.SurName;
      FPersons[FIndex].Age := AValue.Age;
    end;
end;
Gruß vom KodeZwerg
  Mit Zitat antworten Zitat