Delphi Class of

TControlClass = class of TControl;//  此处必须定义一个类引用,创建时需要使用类引用来创建

function CreateControl(ControlClass: TControlClass; const ControlName: string; X, Y, W, H: Integerl;AOwner: TWinControl): TControl;
//ControlClass为TControl 所有的子类
begin
  Result := ControlClass.Create(AOwner);
  with Result do
  begin
    Parent := AOwner;
    Name := ControlName;
    SetBounds(X, Y, W, H);
    Visible := True;
  end;
end;

//用法
CreateControl(TEdit, 'Edit1', 10, 10, 100, 20,Self);
CreateControl(TButton, 'TButton1', 10, 10, 100, 20,Self);

Delphi:用类名创建对象

Delphi在开发一些通用的系统中,需要使用类似于Java中反射的机制,Delphi中有RTTI,但并不十分好用(说实在没特别认真的研究过RTTI), 现在将一种较为简单的根据类名创建实例的方法记录在这里:

我们知道Windows的类管理机制中,允许向系统注册一个类信息并在其它地方使用,在Delphi的VCL中,这种机制被重新定义为允许注册一个可序列化的类,即从TPersistent继承下来的类便拥有这种属性,因此我们在定义一个类的时候注册到系统,通过getClass/FindClass即可从系统中取得这个类的描述并实例化。

例子如下:

TTest = class(TPersistent)

  public

    procedure test; virtual; abstract;

end;

TTestClass = class of TTest;  // 此处必须定义一个类引用,创建时需要使用类引用来创建...

TTestSub1 = class(TTest)

  public

    procedure test; override;

end;

procedureTTestSub1.test;

begin

    showmessage('TTestSub1.test');

end;

initialization

    RegisterClass(TTestSub1);

finalization

    UnregisterClass(TTestSub1); 

调用的时候:

var obj : TTest; 

clsName = 'TTestSub1';

obj := TTestClass(FindClass(clsName)).Create;

obj.test; //此时显示的是'TTestSub1.test',即调用的是TTestSub1中的test方法

说明:这种方法实际上就是一个典型的TEMPLATE METHOD模式。TTest被定义成模板类,通过定义一个操作中的抽象操作在基础类中,而将实际实现延迟到子类中实现。系统不需要知道子类,通过操纵这个基础类即可完成需要的操作。

另外:{$M+/-}可用于RTTI中而不需要定义类从TPersistent继承,但这里必须从TPersistent继承。

原文地址:https://www.cnblogs.com/luckForever/p/7254555.html