【问题标题】:TValue casting to other typeTValue 转换为其他类型
【发布时间】:2016-09-26 13:53:11
【问题描述】:

我有

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;

两次我都收到消息说它无法投射,但为什么?我没看出有什么问题。

【问题讨论】:

    标签: delphi delphi-xe2 rtti tvalue


    【解决方案1】:

    TValue 不是为进行此类转换而设计的。您不能在 Pascal 语言本身无法直接在其之间进行转换的两种不兼容类型之间进行转换。正如String 不能直接分配给IntegerTDateTimeTValue&lt;String&gt; 也不能转换为TValue&lt;Integer&gt;TValue&lt;TDateTime&gt;。使用StrToInt()StrToDateTime() 等转换函数是无可替代的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-23
      • 2017-10-04
      • 1970-01-01
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多