安全的方式在Delphi中为Form分配一个连接到其生命周期的接口对象? [英] Safe way in Delphi for a Form to distribute interface objects tied to its lifetime?

查看:265
本文介绍了安全的方式在Delphi中为Form分配一个连接到其生命周期的接口对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Delphi窗体,它提供了接口对象的功能,代码的其他部分也通过属性的属性获取引用。我不能将接口功能委托给子对象,因为该窗体上的控件/组件的功能太多。我不能使用TAggregatedObject或TContainedObject来连接传递到Form的接口对象的生命周期,因为TForm类不会从TinterfacedObject继承,Delphi不支持多重继承,所以我不能将TInterfacedObject混合到继承链中。如果表单被破坏,而其他一些代码持有Form中传递的接口引用之一,则这种情况可能导致访问冲突。任何人都可以想到这个问题的一个很好的解决方案?

解决方案

您可以将接口委托给子对象,只需拥有该对象包含一个指向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屋!

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