gpt4 book ai didi

Delphi 2010 RTTI 和接口(interface)字段

转载 作者:行者123 更新时间:2023-12-03 15:02:13 25 4
gpt4 key购买 nike

我对 IInterface 类型的属性有疑问。我不知道如何使用 RTTI 为这些属性赋值

这是一个例子:

program Project2;

uses
Forms, RTTI, Windows, TypInfo;
{$R *.res}

type
ITestInterfacedClass = interface
['{25A5B554-667E-4FE4-B932-A5B8D9052A17}']
function GetA: ITestInterfacedClass;
procedure SetA(const Value: ITestInterfacedClass);
property A: ITestInterfacedClass read GetA write SetA;
function GetB: ITestInterfacedClass;
procedure SetB(const Value: ITestInterfacedClass);
property B: ITestInterfacedClass read GetB write SetB;
end;


TTestInterfacedClass = class(TInterfacedObject, ITestInterfacedClass)
private
FA: ITestInterfacedClass;
FB: ITestInterfacedClass;

function GetA: ITestInterfacedClass;
function GetB: ITestInterfacedClass;
procedure SetA(const Value: ITestInterfacedClass);
procedure SetB(const Value: ITestInterfacedClass);

public
property A: ITestInterfacedClass read GetA write SetA;
property B: ITestInterfacedClass read GetB write SetB;
end;


{ ITestInterfacedClass }
....

procedure SetProperty(aLeft: TObject {IInterface}; aNameProp: string; aRight: IInterface);
var
RttiContext: TRttiContext;
RttiType: TRttiType;
RTTIProperty: TRttiProperty;
begin
RttiContext := TRttiContext.Create;

RTTIType := RttiContext.GetType(TTestInterfacedClass);
RTTIProperty := RTTIType.GetProperty(aNameProp);
if RTTIProperty.PropertyType.TypeKind = tkInterface then
RTTIProperty.SetValue(aLeft, TValue.From<IInterface>(aRight));
end;

var
obj1: TTestInterfacedClass;
intf1, intf2, intf3: ITestInterfacedClass;

begin
obj1 := TTestInterfacedClass.Create;
intf1 := obj1;
intf2 := TTestInterfacedClass.Create;
intf3 := TTestInterfacedClass.Create;

intf1.A := intf2;

// intf1.B := intf3;
SetProperty(obj1, 'B', intf3);

end.

我必须写一个类似的 intf1.B:=intf3;或者 obj1.B = intf3;

使用 RTTI。

这可能吗?

UPD这是工作:

procedure SetProperty(aLeft: TObject; aNameProp: string; aRight: IInterface);
var
RttiContext: TRttiContext;
RttiTypeInterface: TRttiInterfaceType;
RTTIProperty: TRttiProperty;
Value: TValue;
begin
RttiContext := TRttiContext.Create;

RTTIType := RttiContext.GetType(aLeft.ClassType);
RTTIProperty := RTTIType.GetProperty(aNameProp);
if RTTIProperty.PropertyType.TypeKind = tkInterface then
begin
TValue.Make(@aRight, RTTIProperty.PropertyType.Handle, Value);
RTTIProperty.SetValue(aLeft, Value);
end;
end;

最佳答案

不幸的是,这不起作用,因为 RTTI.pas 中的接口(interface)转换代码不会调用 QueryInterface。如果您将 TValue 放入 TValue.From<IInterface> ,您无法将其转换为不同接口(interface)类型的 TValue,即使该接口(interface)支持该类型。请随时将其提交给 QC。

使用 TValue.From<ITestInterfacedClass> 创建 TValue不过确实有效。但是这样您就不能使用简单的 SetProperty 例程。

关于Delphi 2010 RTTI 和接口(interface)字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3636384/

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