String TValue & # 8596; Boolean back and forth

I play arround with TValue

I wrote this code in an empty 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 cannot convert back from a string to boolean; In the second line, I get an Invalid Typecast exception.

I use Delphi XE, but this is the same result in Delphi Xe6, which leads me to the conclusion: I am not using TValue correctly.

So please, what am I doing wrong.

+6
source share
2 answers

Although you give Boolean as an example in your question, I'm going to suggest that you are really interested in the complete commonality of the types listed. Otherwise, you simply call StrToBool .

TValue not intended to perform the conversion you are trying to perform. Ultimately, at the lower level, the GetEnumValue and GetEnumName in the System.TypInfo module 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 as follows:

 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, you should use GetEnumName .

+4
source

TValue not intended to convert types that are not compatible with the assignment. It was designed to store values ​​when transporting them to RTTI and to comply with Delphi assignment rules .

Only ToString can output a value in some string representation, but a type that you cannot just assign to a string will also fail when doing this with TValue .

TValue not Variant .

If you want to convert the string to boolean and vice versa, use StrToBool and BoolToStr .

+5
source

Source: https://habr.com/ru/post/980917/


All Articles