gpt4 book ai didi

delphi - 如何枚举对象中的所有属性并获取它们的值?

转载 作者:行者123 更新时间:2023-12-03 14:50:28 29 4
gpt4 key购买 nike

我想枚举所有属性:私有(private)、 protected 、公共(public)等。我希望使用内置设施而不使用任何第三方代码。

最佳答案

Serg 的答案很好,但最好通过跳过某些类型来避免异常:

uses
Rtti, TypInfo;

procedure TForm4.GetObjectProperties(AObject: TObject; AList: TStrings);
var
ctx: TRttiContext;
rType: TRttiType;
rProp: TRttiProperty;
AValue: TValue;
sVal: string;
const
SKIP_PROP_TYPES = [tkUnknown, tkInterface];
begin
if not Assigned(AObject) and not Assigned(AList) then
Exit;

ctx := TRttiContext.Create;
rType := ctx.GetType(AObject.ClassInfo);
for rProp in rType.GetProperties do
begin
if (rProp.IsReadable) and not (rProp.PropertyType.TypeKind in SKIP_PROP_TYPES) then
begin
AValue := rProp.GetValue(AObject);
if AValue.IsEmpty then
begin
sVal := 'nil';
end
else
begin
if AValue.Kind in [tkUString, tkString, tkWString, tkChar, tkWChar] then
sVal := QuotedStr(AValue.ToString)
else
sVal := AValue.ToString;
end;

AList.Add(rProp.Name + '=' + sVal);
end;

end;
end;

关于delphi - 如何枚举对象中的所有属性并获取它们的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8679735/

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