Delphi RTTI SetValue for Enumerations

How to use RTTI to set the value of an enumeration field?

those.

type
  TCPIFileStatus= (fsUnknown, fsProcessed);
  TTest = class
    FStatus: TCPIFileStatus; 
  end;
      ...
  var
    Data: TTest;
    Ctx: TRttiContext;
    Status : TCPIFileStatus;
  begin
    Data := TTest.Create;
    Status := fsProcessed;
    Ctx.GetType(Data.ClassType).GetField('FStatus').SetValue(Data, Status);
  end;

I get "Invalid typecast type".
NB: I need to use RTTI because during development I will not always know the type of the object or the name of the field.

+4
source share
3 answers

you should pass TValuein SetValuetry using this code:

{$APPTYPE CONSOLE}
uses
  Rtti,
  SysUtils;


type
  TCPIFileStatus= (fsUnknown, fsProcessed);
  TTest = class
    FStatus: TCPIFileStatus;
  end;

  var
    Data   : TTest;
    Ctx    : TRttiContext;
    Status : TCPIFileStatus;
    v      : TValue;
begin
  try
    Data := TTest.Create;
    try
      Status := fsProcessed;
      v:= v.From(status); 
      Ctx.GetType(Data.ClassType).GetField('FStatus').SetValue(Data, v);

      // do your stuff
    finally
       Data.Free;
    end;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
+6
source

Another solution to this problem, if you do not know the exact type of enumeration in your function, but instead TypeInfo, should use the TValue Make procedure.

procedure Make(AValue: NativeInt; ATypeInfo: PTypeInfo; out Result: TValue); overload; static;

( XML): TRTTIField/TRTTIProperty.SetValue()

function EnumNameToTValue(Name: string; EnumType: PTypeInfo): TValue;
var
  V: integer;

begin
  V:= GetEnumValue(EnumType, Name);
  TValue.Make(V, EnumType, Result);
end;

, .

+1

Use TValue. From the general method to get a compatible TValue value to go to the SetValue method ...

mmm ... hard to get from words, better code:

type
  TCPIFileStatus= (fsUnknown, fsProcessed);
  TTest = class
    FStatus: TCPIFileStatus;
  end;

procedure TForm2.Button1Click(Sender: TObject);
var
  Data: TTest;
  Ctx: TRttiContext;
  Status : TCPIFileStatus;
  AValue: TValue;
begin
  Data := TTest.Create;
  try
    Status := fsProcessed;
    Ctx.GetType(Data.ClassType).GetField('FStatus').SetValue(Data, TValue.From(Status));
    Assert(Data.FStatus = Status, 'Something wrong on assigning status trough RTTI!');
  finally
    Data.Free;
  end;
end;
0
source

All Articles