Reputation: 223
I have a boolean field which I want to set using MyField.SetValue(Self, MyValue)
. No matter what I tried, I keep getting typecast errors.
The problem is that MyValue always contains an ordinal and is not recognized as containing a boolean. I know that boolean is an enumeration, which is an ordinal, but it should still be possible to set boolean fields and properties using TValue.
I tried the following to initiate MyValue but every time MyValue.IsOrdinal = True
while MyValue.IsBoolean = False
:
MyValue := TValue.From(True);
MyValue := TValue.From<Boolean>(True);
MyBool := True; MyValue := MyValue.From(MyBool);
MyBool := True; MyValue := MyValue.From<Boolean>(MyBool);
MyValue := True;
MyBool := True; MyValue := MyBool;
MyBool := True; TValue.Make(@MyBool, TypeInfo(Boolean), MyValue);
Is there a way to get the TValue to accept that it contains a boolean i.s.o. an ordinal so that MyField.SetValue(Self, MyValue)
will succeed?
Thanks in advance,
Decolaman
Upvotes: 0
Views: 1505
Reputation: 136401
The TValue works fine with boolean values.
Check this sample code
{$APPTYPE CONSOLE}
uses
Rtti,
SysUtils;
Type
TAnyClass=class
AField : Boolean;
end;
Var
Ctx : TRttiContext;
MyValue : TValue;
A : TAnyClass;
MyField : TRttiField;
begin
try
Ctx:=TRttiContext.Create;
A:=TAnyClass.Create;
try
MyField:=Ctx.GetType(TAnyClass).GetField('AField');
MyValue:= MyValue.From(False);
MyField.SetValue(A, MyValue);
Writeln('The Value of AField Is '+BoolToStr(A.AField, True));
MyValue:= MyValue.From(True);
MyField.SetValue(A, MyValue);
Writeln('The Value of AField Is '+BoolToStr(A.AField, True));
finally
A.Free;
Ctx.Free;
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
Upvotes: 3