gpt4 book ai didi

delphi - 获取特定属性的属性值

转载 作者:行者123 更新时间:2023-12-03 14:53:48 24 4
gpt4 key购买 nike

我有一个包含已发布 props 的类,我将其序列化为 XML。

MyAttr = class(TCustomAttribute)
private
FName: string;
public
constructor Create(const Name: string);
property Name: string read FName write FName;
end;

MyClass = class(TPersistent)
private
FClassCaption: string;
published
[MyAttr('Class')]
property ClassCaption: string read FClassCaption write FClassCaption;
end;

由于 XML 大小至关重要,因此我使用属性来为属性提供较短的名称(即我无法定义名为“Class”的属性)。序列化的实现方式如下:

lPropCount := GetPropList(PTypeInfo(Obj.ClassInfo), lPropList);
for i := 0 to lPropCount - 1 do begin
lPropInfo := lPropList^[i];
lPropName := string(lPropInfo^.Name);

if IsPublishedProp(Obj, lPropName) then begin
ItemNode := RootNode.AddChild(lPropName);
ItemNode.NodeValue := VarToStr(GetPropValue(Obj, lPropName, False));
end;
end;

我需要这样的条件:如果属性标记有 MyAttr,则获取“MyAttr.Name”而不是“lPropInfo^.Name”。

最佳答案

您可以使用此函数从给定的属性中获取属性名称(一分钟就写完了,可能需要一些优化):

uses
SysUtils,
Rtti,
TypInfo;

function GetPropAttribValue(ATypeInfo: Pointer; const PropName: string): string;
var
ctx: TRttiContext;
typ: TRttiType;
Aprop: TRttiProperty;
attr: TCustomAttribute;
begin
Result := '';

ctx := TRttiContext.Create;

typ := ctx.GetType(ATypeInfo);

for Aprop in typ.GetProperties do
begin
if (Aprop.Visibility = mvPublished) and (SameText(PropName, Aprop.Name)) then
begin
for attr in AProp.GetAttributes do
begin
if attr is MyAttr then
begin
Result := MyAttr(attr).Name;
Exit;
end;
end;
Break;
end;
end;
end;

这样调用它:

sAttrName:= GetPropAttribValue(obj.ClassInfo, lPropName);

因此,如果此函数返回空字符串,则意味着该属性未用 MyAttr 标记,然后您需要使用“lPropInfo^.Name”。

关于delphi - 获取特定属性的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8239330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com