I have
uses
System.Rtti;
procedure TForm1.BitBtn1Click(Sender: TObject);
var
_UserString: string;
_CastedValue: TValue;
_IntExampleValue: TValue;
_DateTimeExampleValue: TValue;
begin
_UserString := '55';
_IntExampleValue := TValue.From<integer>(-199);
if not TValue.From(_UserString).TryCast(_IntExampleValue.TypeInfo, _CastedValue)
then
ShowMessage('Failed to cast')
else
ShowMessage('Casted successfully');
_UserString := DateTimeToStr(Now);
_DateTimeExampleValue := TValue.From<TDateTime>(Now);
if not TValue.From(_UserString).TryCast(_DateTimeExampleValue.TypeInfo, _CastedValue)
then
ShowMessage('Failed to cast')
else
ShowMessage('Casted successfully');
end;
Both times I get message saying that it failed to cast, but why? I don't see anything wrong.
TValue
is not designed to do those kind of casts. You cannot cast between two incompatible types that the Pascal language itself cannot directly cast between. Just as aString
cannot be directly assigned to anInteger
or aTDateTime
, aTValue<String>
cannot be casted to aTValue<Integer>
or aTValue<TDateTime>
. There is no substitute for using conversion functions likeStrToInt()
andStrToDateTime()
.