Einzelnen Beitrag anzeigen

TiGü

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

AW: auf die Daten der Basisklasse zugreifen

  Alt 21. Aug 2017, 11:24
Delphi-Quellcode:
program Project1;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils,
  System.TypInfo;

type
  TMyClassA = class
  private
    FMyStringA: string;
    FMyIntB: Integer;
  published // <--- wichtig!
    property MyInt: Integer read FMyIntB write FMyIntB;
    property MyString: string read FMyStringA write FMyStringA;
  end;

  TMyClassB = class
  private
    FMyStringB: string;
    FMyIntB: Integer;
  published // <--- wichtig!
    property MyInt: Integer read FMyIntB write FMyIntB;
    property MyString: string read FMyStringB write FMyStringB;
  end;

procedure CopyPropsFromAtoB(A, B: TObject);
var
  PropList: PPropList;
  i, PropCount: Integer;
  PropertyValue: Variant;
  PropertyName: string;
begin
  PropCount := GetPropList(A, PropList);
  if PropCount > 0 then
  begin
    try
      for i := 0 to PropCount - 1 do
      begin
        PropertyName := PropList[i].NameFld.ToString;
        try
          PropertyValue := GetPropValue(A, PropertyName);
          SetPropValue(B, PropertyName, PropertyValue);
        except
          on E: EPropertyConvertError do
          begin
            Writeln(E.ClassName + '.' + E.Message + ' - ' + 'Propertyname: ' + PropertyName);
          end;
          on E: EPropertyError do
          begin
            Writeln(E.ClassName + '.' + E.Message + ' - ' + 'Propertyname: ' + PropertyName);
          end;
          on E: Exception do
          begin
            // Untern Tisch verstecken!
          end;
        end;
      end;
    finally
      FreeMem(PropList);
    end;
  end;
end;

procedure Main;
var
  A: TMyClassA;
  B: TMyClassB;
begin
  A := TMyClassA.Create;
  B := TMyClassB.Create;

  A.MyInt := 666;
  A.MyString := A.MyInt.ToString;

  CopyPropsFromAtoB(A, B);

  Writeln(B.MyInt);
  Writeln(B.MyString);

  A.Free;
  B.Free;
end;

begin
  try
    Main;
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
  Mit Zitat antworten Zitat