Delphi 如何枚举对象中的所有属性并获取其值?
我想枚举所有属性:private、protected、public等。我希望使用内置设施,而不使用任何第三方代码。像这样使用扩展RTTI(当我在XE中测试代码时,我在ComObject属性上遇到异常,所以我插入了try-except块):Delphi 如何枚举对象中的所有属性并获取其值?,delphi,delphi-xe2,Delphi,Delphi Xe2,我想枚举所有属性:private、protected、public等。我希望使用内置设施,而不使用任何第三方代码。像这样使用扩展RTTI(当我在XE中测试代码时,我在ComObject属性上遇到异常,所以我插入了try-except块): Serg的答案很好,但最好通过跳过某些类型来避免异常: uses Rtti, TypInfo; procedure TForm4.GetObjectProperties(AObject: TObject; AList: TStrings); var
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版本的高级功能的绝佳起点:
- 由
- 由
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;