[英]How to Create MDI Child of different type with Generics?
我需要将 MDI Child Forms 创建集中到 Delphi (VCL) 中的唯一过程中。 这个想法是在每次创建 MDI 子窗体时执行一些操作,无论其类型如何,即将其标题名称添加到列表中以访问该 MDI 子窗体。 像这样:
procedure TMainForm<T>.CreateMDIChild(const ACaption : String);
var
Child: T;
begin
{ create a new MDI child window }
Child := T.Create(Application);
Child.Caption := ACaption;
// add this child to the list of active MDI windows
...
end;
procedure TMainForm.Button1Click(Sender : TObject);
begin
CreateMDIChild<TMdiChild1>('Child type 1');
CreateMDIChild<TMdiChild2>('Child type 2');
...
但是,我没有 generics 的经验。 任何帮助我都会很感激。 太感谢了。
您可以使用单元System.Generics.Collections
中的类。 例如,为了解决类似的任务,我使用TObjectList<TfmMDIChild>
,其中TfmMDIChild
我自己的 class。 另一个有用的提示是,您可以制作自己的 class 来保存基于TObjectList
的集合。 我做了这样的事情:
TWindowList = class(TObjectList<TfmMDIChild>)
public
procedure RefreshGrids;
function FindWindow(const AClassName: string; AObjCode: Integer = 0): TfmMDIChild;
procedure RefreshWindow(const AClassName: string; AObjForRefresh: integer = 0; AObjCode: Integer = 0);
procedure RefreshToolBars;
end;
您可以使用 class 约束定义一个 class 来通用创建表单(使用泛型),如下所示:
TGenericMDIForm <T:TForm> = class
class procedure CreateMDIChild(const Name: string);
end;
通过这个实现:
class procedure TGenericMDIForm<T>.CreateMDIChild(const Name: string);
var
Child:TCustomForm;
begin
Child := T.Create(Application);
Child.Caption := Name + ' of ' + T.ClassName + ' class';
end;
现在,您可以使用它来创建 MDIChil forms 不同的类:
procedure TMainForm.Button1Click(Sender: TObject);
begin
TGenericMDIForm<TMdiChild>.CreateMDIChild('Child type 1');
TGenericMDIForm<TMdiChild2>.CreateMDIChild('Child type 2');
end;
使用带有通用TGenericMDIForm <T:TForm> = class
的class constraint
,您可以避免有人尝试使用类似这样的东西TGenericMDIForm<TMemo>.CreateMDIChild('Child type 1');
class 不是TForm
后代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.