bestlong 怕失憶論壇

標題: 根據 RTTI 給子對象的屬性賦值 [打印本頁]

作者: bestlong    時間: 2010-8-9 13:45     標題: 根據 RTTI 給子對象的屬性賦值

通過 RTTI 給對象的屬性賦值相信大家都知道, 相應資料比較多, 但如何用RTTI為含有子對象(如FONT)的屬性賦值?

屬性必須是 published 的, 也就是可以在運行期在 Object Inspector 上設置的屬性
  1. //uses typinfo

  2. //取得對象屬性值,如果存在
  3. function GetObjectProperty(const AObject : TObject; const APropName : string):TObject;
  4. var
  5.   PropInfo: PPropInfo;
  6. begin
  7.   Result := nil;
  8.   PropInfo := GetPropInfo(AObject.ClassInfo, APropName);
  9.   if Assigned(PropInfo) and (PropInfo^.PropType^.Kind = tkClass) then
  10.     Result := GetObjectProp(AObject, PropInfo);
  11. end;

  12. //給整數型態屬性賦值,如果存在
  13. function SetIntegerPropertyIfExists(const AObject : TObject; const APropName : string; const AValue : integer):Boolean;
  14. var
  15.   PropInfo:PPropInfo;
  16. begin
  17.   PropInfo := GetPropInfo(AObject.ClassInfo, APropName);
  18.   if Assigned(PropInfo) and (PropInfo^.PropType^.Kind = tkInteger) then
  19.   begin
  20.     SetOrdProp(AObject, PropInfo, AValue);
  21.     Result := True;
  22.   end else
  23.     Result := False;
  24. end;

  25. //調用,把窗體的 Font.Size 屬性設為 9
  26. procedure TFrmTest.FormCreate(Sender: TObject);
  27. var
  28.   objTemp : TObject;
  29. begin
  30.   objTemp := GetObjectProperty(Self, 'Font');
  31.   if Assigned(objTemp) then
  32.     SetIntegerPropertyIfExists(objTemp, 'Size', 9);
  33. end;
複製代碼





歡迎光臨 bestlong 怕失憶論壇 (http://www.bestlong.idv.tw/) Powered by Discuz! X1.5