如何使用泛型创建不同类型的 MDI 子项?



我需要将MDI子窗体创建集中到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');
...

但是,我没有泛型的经验。任何帮助我将不胜感激。 非常感谢。

您可以使用如下类约束定义一个类来创建表单(使用泛型(:

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表单不同的类:

procedure TMainForm.Button1Click(Sender: TObject);
begin
TGenericMDIForm<TMdiChild>.CreateMDIChild('Child type 1');
TGenericMDIForm<TMdiChild2>.CreateMDIChild('Child type 2');
end; 

class constraint与泛型TGenericMDIForm <T:TForm> = class一起使用,您可以避免有人尝试将类似的东西TGenericMDIForm<TMemo>.CreateMDIChild('Child type 1');用于不是TForm后代的类。

您可以使用单元System.Generics.Collections中的类。例如,为了解决类似的任务,我使用TObjectList<TfmMDIChild>,其中TfmMDIChild我自己的类。 另一个有用的提示,您可以创建自己的类来保存基于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;

最新更新