gpt4 book ai didi

Delphi基于RTTI信息的调用方法

转载 作者:行者123 更新时间:2023-12-03 15:49:17 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com