Delphi Rtti: Explore properties of interfaces?
Is there a way to explore a interface's properties with Rtti?
The following code does not work:
procedure ExploreProps;
var
Ctx: TRttiContext;
RttiType: TRttiType;
RttiProp: TRttiProp;
begin
RttiType := Ctx.GetType(TypeInfo(IMyInterface));
for 开发者_JS百科RttiProp in RttiType.GetProperties do
Writeln(RttiProp.ToString);
end;
Has anyone a solution how to do this correctly?
Interfaces are collections of functions. They don't really have properties the way objects do; that's just a bit of syntactic sugar that the compiler adds for you to make it easier to write code for them. The difference is that on objects, properties allow controlled access to private and protected members, whereas on interfaces, all members are public so there's no need for the properties.
As I known, there is no support for normal interfaces. You could add {$M+} and then try again.
Add this function in your interface
function GetObject: TObject;
and implement it in the class. the use the GetObject function with RTTI routines
var
obj: IPerson;
begin
obj := TPerson.Create;
Count := GetPropList(obj.GetObject.ClassInfo, tkAny, @List);
end;
Please note that your class should be inherited from TInterfacedPersistent not TInterfacedObject
TPerson = class(TInterfacedPersistent, IPerson)
late answer, but you could typecast your interfae to TObject, e.g.
RttiType := Ctx.GetType(TObject(IMyInterface).ClassInfo);
精彩评论