Einzelnen Beitrag anzeigen

TiGü

Registriert seit: 6. Apr 2011
Ort: Berlin
3.070 Beiträge
 
Delphi 10.4 Sydney
 
#5

AW: Generische Array-Propertys

  Alt 23. Feb 2021, 11:20
Delphi-Quellcode:
program Project2;

{$APPTYPE CONSOLE}

{$R *.res}


uses
  System.SysUtils,
  System.Math;

type
  TValue<T> = class
  protected
    a: TArray<T>;
    function GetT(const Index: Integer): T;
    procedure SetT(const Index: Integer; const Value: T);
  end;

  TAStr = class(TValue<string>)
  public
    property s0: string index 0 read GetT write SetT;
  end;

  TAInt = class(TValue<Integer>)
  public
    property i0: Integer index 0 read GetT write SetT;
  end;

  TTest = class
  private
    aStr: TAStr;
    aInt: TAInt;
  public
    constructor Create();
    destructor Destroy; override;
  public
    property MyStrings: TAStr read aStr;
    property MyIntegers: TAInt read aInt;
  end;

function TValue<T>.GetT(const Index: Integer): T;
begin
  if InRange(Index, System.Low(a), System.High(a)) then
  begin
    Result := a[Index];
  end
  else
  begin
    Result := System.Default(T);
  end;
end;

procedure TValue<T>.SetT(const Index: Integer; const Value: T);
begin
  if Index >= Length(a) then
  begin
    SetLength(a, Index + 1);
  end;
  a[Index] := Value;
end;

constructor TTest.Create;
begin
  inherited;
  aStr := TAStr.Create;
  aInt := TAInt.Create;
end;

destructor TTest.Destroy;
begin
  aStr.Free;
  aInt.Free;
  inherited;
end;

procedure TestStrings;
var
  MyStringValue: TAStr;
begin
  MyStringValue := TAStr.Create;
  MyStringValue.s0 := 'Hello World';
  Writeln(MyStringValue.s0);
  MyStringValue.Free;
end;

procedure TestIntegers;
var
  MyIntegerValue: TAInt;
begin
  MyIntegerValue := TAInt.Create;
  MyIntegerValue.i0 := 0815;
  Writeln(MyIntegerValue.i0);
  MyIntegerValue.Free;
end;

procedure TestTest;
var
  MyTest: TTest;
begin
  MyTest := TTest.Create;
  MyTest.aStr.s0 := 'Huhu';
  MyTest.aInt.i0 := 123;
  Writeln(MyTest.aStr.s0);
  Writeln(MyTest.aInt.i0);
  MyTest.Free;
end;

begin
  ReportMemoryLeaksOnShutdown := True;
  try
    TestStrings;
    TestIntegers;
    TestTest;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;

end.
  Mit Zitat antworten Zitat