Delphi 12中能否获取枚举值对应的属性?
Delphi 枚举值获取对应 MappingAttr 属性的规范实现方式
问题说明
我定义了如下枚举类型:
TOAuthSubjectTypes = ( [MappingAttr('public')] ostPublic, [MappingAttr('pairwise')] ostPairwise );
当前我有一个变量存储着ostPairwise,希望直接获取该枚举值对应的MappingAttr属性。目前临时方案是按顺序为枚举类型设置所有属性,通过GetAttributes结合枚举的Ordinal值来获取,但想了解更符合Delphi规范的实现方式。
规范实现方案
利用Delphi的**RTTI(运行时类型信息)**直接定位目标枚举值的属性,无需依赖Ordinal顺序,这是更符合Delphi规范的做法。核心逻辑是通过RTTI上下文获取枚举类型的字段信息,匹配目标枚举值后提取对应的属性。
示例代码
uses System.Rtti, System.TypInfo; function GetMappingAttrFromEnum(const AEnumValue: TOAuthSubjectTypes): string; var Context: TRttiContext; EnumType: TRttiType; Field: TRttiField; Attr: TCustomAttribute; begin Result := ''; Context := TRttiContext.Create; try EnumType := Context.GetType(TypeInfo(TOAuthSubjectTypes)); for Field in EnumType.GetFields do begin if Field.FieldType.TypeKind = tkEnumeration then begin // 匹配目标枚举值的Ordinal值 if Ord(TValue.From(Field.GetValue(nil)).AsType<TOAuthSubjectTypes>) = Ord(AEnumValue) then begin // 遍历字段属性,找到MappingAttr for Attr in Field.GetAttributes do begin if Attr is TMappingAttr then begin Result := TMappingAttr(Attr).Value; // 假设MappingAttr通过Value属性存储字符串 Exit; end; end; end; end; end; finally Context.Free; end; end;
关键说明
- 该方案不依赖枚举值的定义顺序,后续调整枚举项顺序或新增值时,代码无需修改即可正常工作
- 需确保
MappingAttr类继承自TCustomAttribute,且暴露了存储目标字符串的属性(示例中假设为Value) - 若追求性能,可缓存枚举类型的RTTI信息,避免每次调用都重新创建上下文
内容的提问来源于stack exchange,提问作者Arthur Araujo
相关产品推荐
相关产品推荐

