Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Delphi 变量类创建_Delphi - Fatal编程技术网

Delphi 变量类创建

Delphi 变量类创建,delphi,Delphi,我希望通过使用变量类类型及其属性和事件来最小化此代码: 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).Pop

我希望通过使用变量类类型及其属性和事件来最小化此代码:

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类),那么您可以只使用TAncestor的
,并创建该类的特定实例

见:

假设您使用的是VCL,使用FMX时几乎相同 需要注意的是,
TControl
的事件是受保护的,但是我们可以使用interposer类来解决这个问题

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,您可能需要控制。只是一个样本。