释放从TRectangle下降的接口对象 [英] Freeing interfaced object that descends from a TRectangle

查看:162
本文介绍了释放从TRectangle下降的接口对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是接口的新手,并且在我的最新项目中尝试过它们。我有这个(简化的)界面:

I'm new to interfaces and have been trying them out in my latest project. I have this (simplified) interface:

IBoardShape = interface(IInterface)
  function GetColor: integer; 
  procedure SetColor(const aColor: integer);
  property Color: integer read GetColor write SetColor;
end;

有几个课程如下:

TGameRectangle = class(TRectangle, IBoardShape)
private
  FColor: integer;
  function GetColor: integer;
  procedure SetColor(const aColor: integer);
  property Color: integer read GetColor write SetColor;
end;

我有一个工厂,用于在自己的数据模块中创建形状。

I have a factory for creating the shapes in its own data module.

function TdmShapeManager.CreateRect(aParent: TLayout): IBoardShape;
var
  lRect: TGameRectangle;
begin
  lRect := TGameRectangle.Create(self);
  lRect.Parent := aParent; 
  lRect.Align := TAlignLayout.alClient;
  result := lRect as IBoardShape;
end;

结果被添加到 TList< IBoardShape>

所有这些都运行良好,直到我开始尝试在运行时删除形状。我发现 TList [I]:= nil 没有释放该项目,控件只会停留在屏幕上。所以,从这里我不确定。我发现我可以将对象转换为TShape并调用.Free,但这听起来不对。 (我尝试了它并且它可以工作,但它会导致其他问题 - 尝试释放接口时Delphi代码中的错误。)

All of this worked well, until I started trying to remove shapes at run time. I found that TList[I] := nil didn't free the item, the control would just stay on the screen. So, from here I'm not sure to do. I found I can cast the object to a TShape and call .Free on it, but that doesn't sound right. (I tried it and it works but then it leads to other problems - errors inside Delphi code when trying to free an interface.)

有一件事我不确定about:由于我的 TGameRectangle 不是从 TInterfacedObject 下降,我应该自己进行引用计数吗?或者我误解 TInterfacedObject 是为了什么?

One thing that I'm not sure about: Since my TGameRectangle doesn't descend from TInterfacedObject, should I be doing my own reference counting? Or am I misunderstanding what TInterfacedObject is for?

推荐答案

是的,如果如果要使用接口和引用计数,则需要从提供引用计数的类型继承,或者提供自己的 _AddRef _Release <的实现/ code>。

Yes, if you want to use interfaces and reference counting, you need to either inherit from a type that provides reference counting or provide your own implementations of _AddRef and _Release.

_AddRef _Release 你的TGameRectangle有吗?

What do the _AddRef and _Release that your TGameRectangle has do?

这篇关于释放从TRectangle下降的接口对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆