访问 TWinControl 的受保护事件 [英] Accessing protected event of TWinControl

查看:23
本文介绍了访问 TWinControl 的受保护事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,你想分配你自己的事件过程:

imagine, you want to assign your own event procedure:

procedure TSuperObject.DoSomething(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
ShowMessage('Yes, I am doing');
end;

到窗体上的任何 TWinControl.通常,如果表单上有 Panel1 (TPanel),则可以轻松完成:

to any TWinControl on the form. Normally if you have Panel1 (TPanel) on the form, you can do it easy:

Panel1.OnMouseDown:=SuperObject1.DoSomething;

但是如果你想普遍做,怎么做呢?不能访问TWincontrol的受保护成员,这么直观的回答:

But if you want to do it universally, how can it be accomplished? You can not access protected members of TWincontrol, so intuitive answer:

AnyWinControl.OnMouseDown:=SuperObject1.DoSomething;

根本行不通.

RTTI能做到吗?怎么样?

Can it be done by RTTI? How?

谢谢

推荐答案

你不需要 RTTI.

任何代码都可以隐式访问在同一单元中声明的任何类的受保护成员.您可以通过在需要访问该类成员的单元中声明一个新的 TWinControl 后代来利用这一点.声明很简单:

Any code has implicit access to the protected members of any class declared in the same unit. You can take advantage of this by declaring a new TWinControl descendant in the unit that needs access to that class's members. The declaration is very simple:

type
  TProtectedWinControl = class(TWinControl);

然后将任何其他 TWinControl 后代类型转换为该新类型,您将可以访问其任何受保护的字段、属性和方法.TWinControl 的受保护成员是 TProtectedWinControl 的自动受保护成员(通过继承),因此当前单元可以访问它们.

Then type-cast any other TWinControl descendant to that new type, and you'll have access to any of its protected fields, properties, and methods. Protected members of TWinControl are automatically protected members of TProtectedWinControl (through inheritance), so the current unit has access to them.

TProtectedWinControl(AnyWinControl).OnMouseDown := SuperObject1.DoSomething;

请注意,这适用于受保护成员,但不适用于严格受保护成员.

Note that this applies to protected members, but not strict protected members.

这篇关于访问 TWinControl 的受保护事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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