了解运行时类型信息(RTTI)

时间:2023-03-08 17:38:53

RTTI需要引用单元TypeInfo

GetPropInfo 函数用于获得属性的 RTTI 指针 PPropInfo。它有四种重载形式,后面三种重载的实现都是调用第一种形式。AKinds 参数用于限制属性的类型,如果得到的 PPropInfo 不属于指定的类型,则返回 nil。

function GetPropInfo(TypeInfo: PTypeInfo; const PropName: string): PPropInfo;

function GetPropInfo(Instance: TObject; const PropName: string;AKinds: TTypeKinds = []): PPropInfo;

function GetPropInfo(AClass: TClass; const PropName: string;AKinds: TTypeKinds = []): PPropInfo;

function GetPropInfo(TypeInfo: PTypeInfo; const PropName: string;AKinds: TTypeKinds): PPropInfo;

//以下代码,循环修改窗体上的Button组件的Capiton
//方法一:
procedure TForm1.SetCaption;
var
pInfo : PPropInfo;
i:integer;
begin
for i := to Self.ControlCount - do
begin
pInfo := GetPropInfo(Self.Controls[i],'Caption'); //GetPropInfo,根据'Caption'字符串,查找Caption属性
if pInfo <> nil then //如果有
TButton(Self.Controls[i]).Caption:= 'ABC'; //修改Capiton
end;
end;
方法二:
procedure TForm1.SetCaption;
var
pInfo : PPropInfo;
i:integer;
begin
for i := to Self.ControlCount - do
begin
pInfo := GetPropInfo(Self.Controls[i],'Caption');
if pInfo <> nil then
SetPropValue(Self.Controls[i],'Caption','ABC');
end;
end;

参考:http://www.cnblogs.com/key-ok/p/3358804.html