Delphi基于RTTI信息的调用方法

标签 delphi rtti

嘿大家,首先抱歉我的英语不好。 考虑以下内容(不是实际代码):

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

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

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

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

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

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

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

(如果这是 C# 就好了:( )

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

最佳答案

如果字符串属性很简单,正如您所说,那么我假设您从 TypInfo 单元调用 GetStrPropSetStrProp 。使用 GetObjectPropSetObjectProp 可以同样轻松地获取类类型属性。

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

如果您确实不需要该接口(interface),并且您知道 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'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;

关于Delphi基于RTTI信息的调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1396670/

相关文章:

c++ typeid 使用 get() 和 * 为相同的 unique_ptr 返回不同的值

visual-studio - Visual Studio 相当于 Delphi 书签

delphi - 来自delphi IDE专家的如何枚举IDE的形式

delphi - 在 Windows XP 和 Inno Setup 中迭代 SWbemObjectSet

delphi - 如何在 Delphi 中自动设置 bool 值?

delphi - 我对 Delphi-RTTI 有一些麻烦(抽象类、密封类等)

delphi - 如何在单个表单上创建多个单选按钮组?

delphi - 使用 RTTI 获取单元中定义的类和对象的完整列表

c++ - RTTI 支持 C++11(_CPPRTTI 和 __GNUG__)

arrays - RTTI 动态数组 TValue Delphi 2010