bestlong 怕失憶論壇

 

 

搜索
bestlong 怕失憶論壇 論壇 Delphi 根據 RTTI 給子對象的屬性賦值
查看: 3012|回復: 0
go

根據 RTTI 給子對象的屬性賦值 [複製鏈接]

Rank: 9Rank: 9Rank: 9

1#
發表於 2010-8-9 13:45 |只看該作者 |倒序瀏覽 |打印
通過 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;
複製代碼
我是雪龍
http://blog.bestlong.idv.tw
http://www.bestlong.idv.tw
‹ 上一主題|下一主題

Archiver|怕失憶論壇

GMT+8, 2025-5-2 05:07 , Processed in 0.013299 second(s), 10 queries .

Powered by Discuz! X1.5

© 2001-2010 Comsenz Inc.