Главная страница | назад





Article #17225: Using RTTI to determine property of ancestor type

 Question and Answer Database
FAQ: FAQ2225C — Using RTTI to determine property of ancestor type
Category: VCL
Platform: All-32Bit
Product: All-CBuilder,
Question:
Say that I have a pointer to a ClassB that I know decends from
ClassA and I want the value of Property1 from ClassB, however this
property is protected at the ClassA level and therefore not accessable.
How can I use the RTTI ( Run Time Type Information ) to get at the
information in Property1 of ClassB when I don't know _exactly_
what ClassB is?
Answer:
Good question, luckily there are some Delphi runtime library functions
that will let you do this.
The following example responds to a button click and sets the caption
property of a label with the lable of the button (or any other
control decended from TControl) using RTTI to figure out what
sort of pointer to use (sort of).
NOTE: EmptyStr is a string type constant that contains NULL.
#include 
//--------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//--------------------------------------------------------------------
AnsiString TForm1::GetCaption(TControl *AComp)
{
PPropInfo propInfo;
AnsiString result;
AnsiString theCaption;
result = EmptyStr;
if (AComp == NULL)
return result;
propInfo = GetPropInfo((TTypeInfo*)(AComp->ClassInfo()), "Caption");
if (propInfo != NULL)
result = GetStrProp(AComp, propInfo);
return result;
}
//--------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Label1->Caption = GetCaption(dynamic_cast(Sender));
}
//--------------------------------------------------------------------
This information was gleaned from the Borland Newsgroups as a submission
by Ralph Friedman of the amazing Team B.
6/24/99 9:30:42 AM

Last Modified: 01-SEP-99