我知道我很久以前就能做到这一点,所以一定有可能.
我想将一个项目(例如组件的align属性alNone)转换为我可以保存,显示的字符串等等.我知道我可以获得字节值并得出我自己的文本,但我确信有更直接的方法.
比如我想......
var S:string;
S:= somehow(Form.Align);
ShowMessage(S);
Run Code Online (Sandbox Code Playgroud)
然而,在某种程度上,我将表单的align属性的设置转换为字符串,例如"alNone".
Delphi XE3,System.Rtti.pas
我需要访问两个私有类函数,但我已经读过如果我修改RTL单元的接口部分,那么我需要重新编译所有的RTL.不适合胆小的心!
两个私有类函数在System.Rtti.pas中:
class function GetName<T{: enum}>(AValue: T): string; reintroduce; static;
class function GetValue<T{: enum}>(const AName: string): T; static;
Run Code Online (Sandbox Code Playgroud)
TRttiEnumerationType = class(TRttiOrdinalType)
private
function GetMaxValue: Longint; override;
function GetMinValue: Longint; override;
function GetUnderlyingType: TRttiType;
constructor Create(APackage: TRttiPackage; AParent: TRttiObject; var P: PByte); override;
{$HINTS OFF}
function GetNames: TArray<string>;
class function GetName<T{: enum}>(AValue: T): string; reintroduce; static;
class function GetValue<T{: enum}>(const AName: string): T; static;
{$HINTS ON}
public
property UnderlyingType: TRttiType read GetUnderlyingType;
end;
Run Code Online (Sandbox Code Playgroud) 我有一个使用Enum Generic Type的Generic类.我的问题如何在该类型的实例上使用GetEnumName?
我已经创建了一个小型演示类来说明问题:
type
TEnumSettings<TKey: record > = class
private
Key: TKey;
public
constructor Create(aKey: TKey);
function ToString: string; override;
end;
uses
TypInfo;
{ TEnumSettings<TKey> }
constructor TEnumSettings<TKey>.Create(aKey: TKey);
begin
if PTypeInfo(System.TypeInfo(TKey)).Kind <> tkEnumeration then
Exception.Create(string(PTypeInfo(System.TypeInfo(TKey)).Name) + ' is not an Enumeration');
Key := aKey;
end;
function TEnumSettings<TKey>.ToString: string;
begin
Result := GetEnumName(System.TypeInfo(TKey), Integer(Key)) <== HERE I get a compile error: Invalid type cast
end;
Run Code Online (Sandbox Code Playgroud)
我正在使用Delphi XE.那可以这样做吗?如果是这样怎么样?
我无法根据名称而不是序数值获取枚举类型。我需要在类属性的 RTTI 循环内执行此操作。我尝试过使用 GetEnumName 和 TRTTIEnumerationType.GetName,但我似乎无法从 TRTTIProperty 实例将这些东西组合在一起。
请帮助?(下面的框架代码示例)
用途
RTTI、类型信息;
类型
TCustomColor = (ccBlack, ccBrown, ccBlue);
TMyClass = 类
民众
属性自定义颜色:TCustomColor;
结尾;
程序输出;
变量
rc:TRTTIContext;
rt : TRTTI 类型;
rp : TRTTI 属性;
mc : TMyClass;
开始
mc.CustomColor := ccBlue;
rt := rc.GetType(mc.ClassType);
对于 rt.GetProperties 中的 rp 做
如果 rp.PropertyType.TypeKind = tkEnumeration 那么
开始
// TODO: 从属性中检索“ccBlue”
结尾;
结尾;
程序输入;
变量
n、s:字符串;
o:T 对象;
rc:TRTTIContext;
rt : TRTTI 类型;
开始
n := '自定义颜色';
s := 'ccBlue';
// 注意:o 是从它的类类型的字符串实例化的 …