delphi - 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);
但我希望提供一个也适用于其他类型的通用函数。
解决方案
这似乎做到了:
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 复制了这个想法)
推荐阅读
- reporting-services - 从 Reporting Services 迁移到 SSDT
- kubernetes - Kubernetes 不创建证书
- .net - 不同的 RedirectURL Google OAuth
- react-native - 更改 FlatList 的唯一 onPressed 项的样式
- c# - RabbitMQ.Fakes 单元测试 C#,System.TypeLoadException
- scala - [RollOverStatus] = 'Y' then 'Yes' Else 'No' end as RollOverStatus 如何在 spark-scala 2.4.0 中编写
- asp.net - 当用户在请求期间强制退出浏览器时,w3wp 的 CPU 使用率突然升高
- javascript - 什么语法错误导致函数的“文本”在这个 JS 闭包中返回,而不是让它递增?
- java - 我们如何从另一个不包含该片段的类中调用一个片段?
- jquery-ui - jQueryUI selectmenu - 设置选择的选项