我希望通过使用变量类类型及其来自:
的属性和事件来最小化此代码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;
当然代码比这长得多,但我使用了样本!!
答案 0 :(得分:2)
有两种方法可以做到这一点:
如果类具有共同的祖先(非常可能是VCL或FMX类),那么您可以使用npm install
并创建该类的特定实例。
假设您使用的是VCL,使用FMX几乎一样
有一点需要注意,class of TAncestor
的事件受到保护,但我们可以使用插入类来绕过它。
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;
另一种方法使用RTTI,但我不建议这样做,除非你使用的是没有共同祖先的物体。
如果这对你来说是真的,请告诉我,我会扩大答案。