安全的方式在Delphi中为Form分配一个连接到其生命周期的接口对象? [英] Safe way in Delphi for a Form to distribute interface objects tied to its lifetime?
问题描述
您可以将接口委托给子对象,只需拥有该对象包含一个指向Form的内部指针,所以它可以在需要时访问Form的控件,没有什么不同,你现在已经在做。
你可以使用 TAggregateObject
或 TContainedObject
为您的需要。他们不需要从 TInterfacedObject
派生表单。他们所需要的只是一个 IInterface
接口指针,而 TComponent
源自 IInterface
(并覆盖 _AddRef()
和 _Release()
以禁用引用计数),所以你可以将表单本身(作为 TComponent
descendant)作为必需的 IInterface
指针。
剩下唯一的问题 - 表单关闭,而其他代码正在保存活动接口引用。最简单的解决方法是:1)在窗体关闭时,将代码重写为不保留这些引用,或者2)不允许窗体关闭,直到引用被释放为止。
I have a Delphi Form that provides the functionality behind an interface object that other parts of the code get references too via a property belonging to the Form. I can't delegate the interface functionality to a child object because too much of that functionality is serviced by controls/components on the form. I can't use TAggregatedObject or TContainedObject to link the lifetime of the interfaced objects being passed around to the Form because the TForm class does not inherit from TinterfacedObject and Delphi does not support multiple inheritance so I can't mix in TInterfacedObject into the inheritance chain. This situation can lead to access violations if a Form gets destroyed while some other code holds one of the interface references passed out by the Form. Can anyone think of a good solution to this problem?
You can delegate the interface to a child object, just have that object contain an internal pointer to the Form so it can access the Form's controls when needed, no different then you are already doing right now.
You can use TAggregateObject
or TContainedObject
for your needs. They do not require the Form to derive from TInterfacedObject
. All they do require is an IInterface
interface pointer, and TComponent
derives from IInterface
(and overrides the _AddRef()
and _Release()
to disable reference counting), so you can pass the Form itself (being a TComponent
descendant) as the required IInterface
pointer.
That leaves the only issue remaining - the Form closing while active interface references are being held by other code. The simpliest solution is to either 1) rewrite that code to not hold on to those references while the Form is closing, or 2) don't allow the Form to close until those references have been released.
这篇关于安全的方式在Delphi中为Form分配一个连接到其生命周期的接口对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!