根据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上设置的属性
                                

查看回复