Delphi RTTI:获取属性的类 [英] Delphi RTTI: Get property's class
问题描述
使用Delphi 2010和RTTI,我知道如何获取对象的类类型以及如何获取/设置对象属性的值和类型,但是如何确定属性来自继承链中的哪个类? ?我想以不同于主类的方式使用基类的属性。
Using Delphi 2010 and RTTI, I know how to get the class type of an object and how to get/set the value and type of an object's properties, but how do you determine which class in the inheritance chain a property came from? I want to use the properties of a base class differently than the main class.
考虑以下代码:
TClassBase = class(TObject)
published
property A: Integer;
end;
TClassDescendant = class(TClassBase)
published
property B: Integer;
end;
procedure CheckProperties(Obj: TObject);
var
ctx: TRttiContext;
objType: TRttiType;
Prop: TRttiProperty;
begin
ctx := TRttiContext.Create;
objType := ctx.GetType(Obj.ClassInfo);
for Prop in objType.GetProperties do begin
if Prop.GetClassType is TClassBase then
// do something special with base class properties
else
// standard functionality on all other properties
end;
end;
问题是属性没有GetClassType。 ClassType仅返回TRttiInstancePropertyEx而不是属性所属类的名称。
The problem is there is no GetClassType for the properties. ClassType just returns TRttiInstancePropertyEx instead of the name of the class to which the property belongs.
推荐答案
另一种选择是使用 TRttiProperty
,您可以从此处访问该类该属性是的一部分。
Another option is use the Parent
property of the TRttiProperty
, from here you can access to the class which the property is part of.
{$APPTYPE CONSOLE}
{$R *.res}
uses
Rtti,
SysUtils;
type
TClassBase = class(TObject)
private
FA: Integer;
published
property A: Integer read FA;
end;
TClassDescendant = class(TClassBase)
private
FB: Integer;
published
property B: Integer read FB;
end;
procedure CheckProperties(Obj: TObject);
var
ctx: TRttiContext;
objType: TRttiType;
Prop: TRttiProperty;
begin
ctx := TRttiContext.Create;
objType := ctx.GetType(Obj.ClassInfo);
for Prop in objType.GetProperties do
if TRttiInstanceType(Prop.Parent).MetaclassType=TClassBase then
Writeln(Format('The property %s is declarated in the TClassBase class',[Prop.Name]))
else
Writeln(Format('The property %s is not declarated in the TClassBase class',[Prop.Name]))
end;
begin
try
//CheckProperties(TClassBase.Create);
CheckProperties(TClassDescendant.Create);
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
这篇关于Delphi RTTI:获取属性的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!