3

大家好,首先对不起我的英语不好。考虑以下(不是实际代码):

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

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

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

我正在使用 RTTI 设置“MyOtherClass”属性。对于字符串属性很容易,但我的问题是:

如何获取对“数据”(MyClass)属性的引用,以便调用该Go()方法?

我想做这样的事情(伪代码):

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

(如果这只是 C# :( )

PS .:这是在delphi 7中(我知道,甚至更糟)

4

2 回答 2

4

如您所说,如果字符串属性很简单,那么我假设您是从单元调用GetStrProp和调用的。使用和可以同样简单地使用类类型属性。SetStrPropTypInfoGetObjectPropSetObjectProp

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

如果你真的不需要接口,并且你知道data属性有 type TMyClass,那么你可以更直接一点:

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

这要求属性具有非空值。

如果您不知道您想要的属性的名称,那么您可以使用其他一些东西TypInfo来搜索它。例如,这是一个函数,它将查找具有实现的值的对象的所有已发布属性IMyInterfaceGo它不按特定顺序调用它们中的每一个。

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's 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;
于 2009-09-09T00:22:30.587 回答
2

您可以通过调用 GetPropInfos(MyClass.ClassInfo) 获取所有已发布属性的数组。这是一个 PPropInfo 指针数组。您可以通过调用 GetTypeData 从 PPropInfo 中获取特定类型的数据,它返回 PTypeData。它指向的记录将包含您要查找的有关类参考的信息。

于 2009-09-08T23:02:56.517 回答