I'm playing arround with TValue
I've written this code in a blank project:
uses
RTTI;
procedure TForm1.FormCreate(Sender: TObject);
var
s: string;
b: Boolean;
begin
s := TValue.From<Boolean > (True).ToString;
b := TValue.From<string > (s).AsType<Boolean>;
end;
But I can not convert back from string to boolean; I get an Invalid Typecast exception in the second line.
I'm using Delphi XE but it is the same result in Delphi Xe6 which leads me to the conclusion: I'm using TValue wrong.
So please what am I doing wrong.
Although you give Boolean
as the example in your question, I'm going to assume that you are really interested in the full generality of enumerated types. Otherwise you would just call StrToBool
.
TValue
is not designed to perform the conversion that you are attempting. Ultimately, at the low-level, the functions GetEnumValue
and GetEnumName
in the System.TypInfo
unit are the functions that perform these conversions.
In modern versions of Delphi you can use TRttiEnumerationType
to convert from text to an enumerated type value:
b := TRttiEnumerationType.GetValue<Boolean>(s);
You can move in the other direction like this:
s := TRttiEnumerationType.GetName<Boolean>(b);
These methods are implemented with calls to GetEnumValue
and GetEnumName
respectively.
Older versions of Delphi hide TRttiEnumerationType.GetValue
and TRttiEnumerationType.GetName
as private methods. If you are using such a version of Delphi then you should use GetEnumName
.
TValue
is not meant to convert types that are not assignment compatible. It was designed to hold values while transporting them in the RTTI and to respect the assignment rules of Delphi.
Only ToString
can output the value in some string representation but a type that you cannot simply assign a string to will also fail when doing that with TValue
.
TValue
is not a Variant
.
If you want to convert a string to boolean and back then use StrToBool
and BoolToStr
.
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