DelphiのRTTI(実行時型情報)を復習する。
■コンポーネントプロパティの型情報を取得する
- TypInfo.TPropInfo
Delphiでは実行時にコンポーネントの型情報を取得することができる。
コンポーネントプロパティの型情報のレコードが「TypInfo.TPropInfo」である。 -
TPropInfo レコードへのポインタ。
type PPropInfo = ^TPropInfo; -
コンポーネントからプロパティの情報を取得する。
指定したプロパティが存在しない場合には、nil ポインタが返されます。例:Edit1のColorプロパティを取得する
var PropInfo: PPropInfo; begin PropInfo := GetPropInfo(Edit1, 'Color');
■コンポーネントプロパティに値を設定する
- TypInfo.SetOrdProp
コンポーネントプロパティの値を設定する。
例:Edit1のColorプロパティの値をclRedに設定する。
var PropInfo: PPropInfo; begin PropInfo := GetPropInfo(Edit1, 'Color'); SetOrdProp(Edit1, PropInfo, clRed);
サンプルプログラム:フォーム上のコンポーネントのColorプロパティの値をclRedに設定する
var
I: Integer;
PropInfo: PPropInfo;
begin
for I := 0 to ComponentCount - 1 do
begin
PropInfo := GetPropInfo(Components[I].ClassInfo, 'Color');
if PropInfo<> nil then
begin
SetOrdProp(Components[I], PropInfo, clRed);
end;
end;
end;
Colorプロパティを持つコンポーネントのColorプロパティの値がclRedになった。
■コンポーネントがもつプロパティの情報を取得する
- TypInfo.TPropList
PPropInfoの配列。
-
TPropListへのポインタ。
-
コンポーネントプロパティのリストを取得する。
サンプルプログラム:Edit1のプロパティ名をすべてListBoxに出力する
var
I: Integer;
Cnt: Integer;
PropList : PPropList;
begin
Cnt := GetPropList(Edit1, PropList);
for I := 0 to Cnt - 1 do
begin
ListBox1.Items.Add(string(PropList[I].Name));
end;
end;
サンプルプログラム:フォーム上のコンポーネントのCaptionの値を大文字にする
var
I: Integer;
PropInfo: PPropInfo;
Caption: String;
begin
for I := 0 to ComponentCount - 1 do
begin
PropInfo := GetPropInfo(Components[I].ClassInfo, 'Caption');
if PropInfo<> nil then
begin
//コンポーネントのCaptionの値を取得する
Caption := GetStrProp(Components[I], 'Caption');
//Captionの値を大文字にして設定する
SetStrProp(Components[I], PropInfo, UpperCase(Caption));
end;
end;
end;
■オブジェクト型のコンポーネントプロパティ
- TypInfo.GetObjectProp
オブジェクト型であるコンポーネントプロパティの値を返す
-
オブジェクト型であるコンポーネントプロパティの値を設定する
■サンプルプログラム
TypInfo.SetObjectPropを使った興味深いプログラムが「実行時型情報を使ったプロパティへのアクセス – Delphi の話 (フェンリル | デベロッパーズブログ)」で紹介されています。
実行時に型情報を使ってリソースのデータをプロパティに設定しています。
Pingback: DelphiのRTTI(実行時型情報)を復習する。その2(RTTIユニット) « 山本隆の開発日誌