How do I use RTTI to set an enumerated field's value ?
I.e.
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 class typecast."
NB:I need to use RTTI because I will not always know the object type or field name at design time.
you must pass a TValue
to the SetValue
method try 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.
Another solution to this problem, in the case you don't know the exact enum type on your function but instead it's TypeInfo, is to use TValue's Make procedure.
procedure Make(AValue: NativeInt; ATypeInfo: PTypeInfo; out Result: TValue); overload; static;
Here is an example (From an XML config parser): This is later used for a TRTTIField/TRTTIProperty.SetValue()
function EnumNameToTValue(Name: string; EnumType: PTypeInfo): TValue;
var
V: integer;
begin
V:= GetEnumValue(EnumType, Name);
TValue.Make(V, EnumType, Result);
end;
Hope this helps you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With