可变类创建
问题描述:
我想利用可变类类型,以尽量减少此代码,它是从属性和事件:可变类创建
if ctype='T' then
begin
C:= TTimeEdit.Create(self);
(c as TTimeEdit).OnMouseUp:= Panel2MouseUp;
(c as TTimeEdit).OnMouseDown:= Panel2MouseDown;
(c as TTimeEdit).OnMouseMove:= Panel2MouseMove;
(c as TTimeEdit).PopupMenu:= PopupMenu1;
end;
if ctype='S' then
begin
C:= TTabSheet.Create(self);
(c as TTabSheet).OnMouseUp:= Panel2MouseUp;
(c as TTabSheet).OnMouseDown:= Panel2MouseDown;
(c as TTabSheet).OnMouseMove:= Panel2MouseMove;
(c as TTabSheet).PopupMenu:= PopupMenu1;
end;
看起来像这样:
VAR VARCLS:TCLASS;
BEGIN
if ctype='S' then
VARCLS:=TTabSheet;
if ctype='T' then
VARCLS:=TTimeEdit;
C:= VARCLS.Create(self);
(c as VARCLS).OnMouseUp:= Panel2MouseUp;
(c as VARCLS).OnMouseDown:= Panel2MouseDown;
(c as VARCLS).OnMouseMove:= Panel2MouseMove;
(c as VARCLS).PopupMenu:= PopupMenu1;
end;
确保代码要长得多比这个,但我用了一个样本!
答
有两种方法可以做到这一点:
如果类有一个共同的祖先(很可能为VCL或FMX类),那么你可以只使用一个class of TAncestor
并创建该类的一个特定实例。
假设你正在使用VCL,它几乎是用FMX 有一个警告的TControl
事件受到保护一样,但我们可以用一个中介类要解决这个问题。
type
TMyClass = class of TControl;
//interposer class, makes events public;
TPublicControl = class(TControl)
public
property OnMouseUp; //a 'naked' property redeclares the existing
property OnMouseDown; //events and properties as public
property OnMouseMove;
property PopupMenu;
end;
function CreateThing(Owner: TControl; MyType: TMyClass): TControl;
begin
Result:= MyType.Create(Owner);
TPublicControl(Result).OnMouseUp:= Panel2MouseUp;
....
end;
该例程不必知道类型,仍然返回一个特定的创建实例。
你调用这个例程,像这样:
var
MyEdit: TEdit;
begin
MyEdit:= TEdit(CreateThing(Panel, TEdit));
另一种方法是使用RTTI,但我不会推荐,除非你使用的是没有一个共同的祖先对象。
如果您确实如此,请告诉我,我会扩大答案。
使用RTTI来实现这个 –
我想要一只小马:-)你真的需要问一个实际的问题,而不是给出一个需求列表。你试过什么了?你从哪里被困住了? –
如果所有类都有一个共同的父类,并且来自该类的所有事件(就像您的情况一样),只需创建一个'程序AssignEvents(const AObject:TWinControl);'并在其中设置所需的事件。无需单独投射。对于FMX你可能需要TControl。只是一个样本。 – Marcodor