gpt4 book ai didi

delphi - 发布接口(interface)与内部接口(interface)问题

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

我这里有一个代码:

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
IInnerTest = interface (IInterface)
procedure DoSth;
end;

TRekScannerData = record
Source: Integer;
Device: IInnerTest;
end;

ITest = interface (IInterface)
procedure DoSth;
end;

ATest = class(TInterfacedObject, ITest)
private
FInner: Array of TRekScannerData;
public
procedure DoSth;
constructor Create();
Destructor Destroy();override;
end;

AInnerTest = class (TInterfacedObject, IInnerTest)
private
FMainInt: ITest;
public
constructor Create(MainInt: ITest);
procedure DoSth;
Destructor Destroy();override;
end;

TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
test: ITest;

implementation

{$R *.dfm}

{ ATest }

constructor ATest.Create;
begin
SetLength(FInner, 1);
FInner[0].Device := AInnerTest.Create(self);
//<----- Here is the reason. Passing main interface to the inner interface.
end;

destructor ATest.Destroy;
begin
beep;
inherited;
end;

procedure ATest.DoSth;
begin
//
end;

{ AInnerTest }

constructor AInnerTest.Create(MainInt: ITest);
begin
FMainInt := MainInt;
end;

destructor AInnerTest.Destroy;
begin
beep;
inherited;
end;

procedure AInnerTest.DoSth;
begin
//
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
test := ATest.Create;
test.DoSth;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
test := nil;
end;

end.

问题是当 test 赋值为 nil 时,Destroy 没有被调用;

我想通过一条语句释放所有内部接口(interface)...是否可以?或者我是否需要在 nil 之前使用另一种方法销毁所有内部结构?

编辑

类结构如下:

Var x = ITest(ATest class) has ->
Inner Interface: IInnerTest(AInnerTest class) which has reference to:
ITest(ATest class)

Nil'ing x 不会释放所有结构...

最佳答案

您有一个循环引用。您的 IInnerTest 实现包含对 ITest 的引用。并且您的 ITest 实现包含对 IInnerTest 的引用。而这种循环引用意味着接口(interface)引用计数永远不会为零。

此问题的正常解决方案是使用弱引用。一些有用的链接:

关于delphi - 发布接口(interface)与内部接口(interface)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14138826/

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