Einzelnen Beitrag anzeigen

Benutzerbild von Stevie
Stevie

Registriert seit: 12. Aug 2003
Ort: Soest
4.009 Beiträge
 
Delphi 10.1 Berlin Enterprise
 
#8

AW: Verständnisfrage zu TValue

  Alt 4. Mär 2020, 17:21
Delphi-Quellcode:
{$APPTYPE CONSOLE}

uses
  Rtti, SysUtils, Spring;

type
  TMyObject = class
  private
    FCount: Integer;
    FDateTime: TDateTime;
    FActive: Boolean;
  public
    property Active: Boolean read FActive write FActive;
    property Count: Integer read FCount write FCount;
    property DateTime: TDateTime read FDateTime write FDateTime;
  end;

var
  m: TMyObject;
  props: TArray<TRttiProperty>;
  values: TArray<string>;
  i: Integer;
  ISO8601FormatSettings: TFormatSettings;
begin
  m := TMyObject.Create;
  m.Active := True;
  m.Count := 42;
  m.DateTime := Now;
  props := TType.GetType(TMyObject).GetDeclaredProperties;
  SetLength(values, Length(props));
  for i := 0 to High(props) do
    values[i] := props[i].GetValue(m).ToString;

  for i := 0 to High(props) do
    Writeln(props[i].Name, ': ', values[i]);
  Writeln;

  values[0] := 'False';
  values[1] := '12345';
  values[2] := '2020-12-31 12:34:00'; // geht sogar im ISO8601 format ...

  // ... man muss nur ein entsprechendes formatsettings an Convert übergeben
  ISO8601FormatSettings := TFormatSettings.Create;
  ISO8601FormatSettings.DateSeparator := '-';
  ISO8601FormatSettings.TimeSeparator := ':';
  ISO8601FormatSettings.ShortDateFormat := 'YYYY-MM-DD';
  ISO8601FormatSettings.ShortTimeFormat := 'hh:mm:ss';
  ISO8601FormatSettings.DecimalSeparator := '.';
  ISO8601FormatSettings.TimeAMString := '';
  ISO8601FormatSettings.TimePMString := '';

  for i := 0 to High(props) do
    props[i].SetValue(m, TValue.From(values[i]).Convert(props[i].PropertyType.Handle, ISO8601FormatSettings));

  Writeln('Active: ', m.Active, sLineBreak, 'Count: ', m.Count, sLineBreak, 'DateTime: ', DateTimeToStr(m.DateTime));
  Readln;
end.
Stefan
“Simplicity, carried to the extreme, becomes elegance.” Jon Franklin

Delphi Sorcery - DSharp - Spring4D - TestInsight
  Mit Zitat antworten Zitat