Delphi call method based on RTTI information

Hi everyone, first sorry for my bad english. Consider the following (not actual code):

IMyInterface = Interface(IInterfce)
  procedure Go();
end;

MyClass = class(IMyInterface)
  procedure Go();
end;

MyOtherClass = class
published
  property name: string;
  property data: MyClass;
end;

I set the "MyOtherClass" properties using RTTI. For a string property, this is easy, but my question is:

How can I get a reference to the "data" property (MyClass) so that I can call the method Go()?

I want to do something like this (pseudocode):

for i:= 0 to class.Properties.Count  
  if (propertyType is IMyInterface) then
    IMyInterface(class.properties[i]).Go()

(if only it was C # :()

PS: this is in delphi 7 (I know even worse)

+3
source share
2 answers

string , , , GetStrProp SetStrProp TypInfo. GetObjectProp SetObjectProp.

if Supports(GetObjectProp(Obj, 'data'), IMyInterface, Intf) then
  Intf.Go;

, , data TMyClass, :

(GetObjectProp(Obj, 'data') as TMyClass).Go;

, .

, TypInfo . , , , , IMyInterface; Go .

procedure GoAllProperties(Other: TObject);
var
  Properties: PPropList;
  nProperties: Integer;
  Info: PPropInfo;
  Obj: TObject;
  Intf: IMyInterface;
  Unk: IUnknown;
begin
  // Get a list of all the object published properties
  nProperties := GetPropList(Other.ClassInfo, Properties);
  if nProperties > 0 then try
    // Optional: sort the list
    SortPropList(Properties, nProperties);

    for i := 0 to Pred(nProperties) do begin
      Info := Properties^[i];
      // Skip write-only properties
      if not Assigned(Info.GetProc) then
        continue;

      // Check what type the property holds
      case Info.PropType^^.Kind of
        tkClass: begin
          // Get the object reference from the property
          Obj := GetObjectProp(Other, Info);
          // Check whether it implements IMyInterface
          if Supports(Obj, IMyInterface, Intf) then
            Intf.Go;
        end;

        tkInterface: begin
          // Get the interface reference from the property
          Unk := GetInterfaceProp(Obj, Info);
          // Check whether it implements IMyInterface
          if Supports(Unk, IMyInterface, Intf) then
            Intf.Go;
        end;
      end;
    end;
  finally
    FreeMem(Properties);
  end;
end;
+4

, GetPropInfos (MyClass.ClassInfo). PPropInfo. PPropInfo, GetTypeData , PTypeData. , , , .

+2

Source: https://habr.com/ru/post/1717195/


All Articles