您当前的位置:delphi教程 > Delphi笔记 >  根据RTTI给子对象的属性赋值

根据RTTI给子对象的属性赋值

通过RTTI给对象的属性赋值相信大家都知道,相应资料比较多,
但如何用RTTI为含有子对象(如FONT)的属性赋值?

//uses typinfo

//取得对象属性值,如果存在
function GetObjectProperty(
    const AObject   : TObject;
    const APropName : string
    ):TObject;
var
  PropInfo:PPropInfo;
begin
  Result  :=  nil;
  PropInfo:=GetPropInfo(AObject.ClassInfo,APropName);
  if Assigned(PropInfo) and
      (PropInfo^.PropType^.Kind = tkClass) then
    Result  :=  GetObjectProp(AObject,PropInfo);
end;

//给整型属性赋值,如果存在
function SetIntegerPropertyIfExists(
    const AObject   : TObject;
    const APropName : string;
    const AValue    : integer
    ):Boolean;
var
  PropInfo:PPropInfo;
begin
  PropInfo:=GetPropInfo(AObject.ClassInfo,APropName);
  if Assigned(PropInfo) and
      (PropInfo^.PropType^.Kind = tkInteger) then
  begin
    SetOrdProp(AObject,PropInfo,AValue);
    Result:=True;
  end else
    Result:=False;
end;

//调用,把窗体的Font.Size属性设为9
procedure TFrmTest.FormCreate(Sender: TObject);
var
  objTemp : TObject;
begin
  objTemp :=  GetObjectProperty(Self,'Font');
  if Assigned(objTemp) then
    SetIntegerPropertyIfExists(objTemp,'Size',9);
end;

//属性必须是published的,也就是可以在运行期在Object Inspector上设置的属性


查看回复
关于我们 | 网站地图 | 广告刊登 | 友情链接
Copyright ©2008 - 2010  Delphi2007.net  ,All Rights Reserved  粤ICP备09038647号
业务联系:allceoad#gmail.com QQ:20008835 最佳分辨率 1024×768