首页 > 解决方案 > TValue.AsType在 Delphi 中使用枚举类型

问题描述

用 Delphi 写这个

uses System.Classes;
...
var
  A: TAlignment;
  Value: TValue;
begin
  Value := 0;
  A := Value.AsType<TAlignment>();
end;

在 AsType 引发 EInvalidCast。

有没有办法使用 TValue 从整数值转换为任何枚举类型?

这当然是显而易见的答案:

A := TAlignment(Value);

但我希望提供一个也适用于其他类型的通用函数。

标签: delphienumstvalue

解决方案


这似乎做到了:

  if (PTypeInfo(TypeInfo(TAlignment))^.Kind = tkEnumeration) and (Value.TypeInfo.Kind = tkInteger ) then
    case System.TypInfo.GetTypeData(TypeInfo(TAlignment))^.OrdType of
      otUByte, otSByte: PByte(@A)^ := Value.AsInteger;
      otUWord, otSWord: PWord(@A)^ := Value.AsInteger;
      otULong, otSLong: PInteger(@A)^ := Value.AsInteger;
    end
  else
    A := Value.AsType<TAlignment>();

其中 TAlignment 也可以是泛型函数中的 T。

(从 TRttiEnumerationType.GetValue 复制了这个想法)


推荐阅读