Delphi Class of

转载自:http://blog.sina.com.cn/s/blog_6250a9df0101sqem.html

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继承。


以下部分转载自:http://www.cnblogs.com/yangxuming/p/6707459.html

Type
  TControlCls = Class of TControl;
function CreateComponent(ControlCls: TControlCls): TControl;
begin
  result:=ControlCls.Create(Form1);
  ...
end;
function CreateComponent(ControlCls: TControl): TControl;
begin
  result:=ControlCls.Create(Form1);
  ...
end;

前者要求传入一个 类, 而后者要求传入一个 对象(类的实例)
type 
MyClassRef=calss of CMyClass //表示MyClassRef为指向CMyClass或其父类的指针

类的引用就像指向类的指针一样
类引用就是类的类型,可以声明一个类引用变量赋给它一个类,可以通过这个变量创建对象的实例。

类之类
当你不确定调用的类模型时候用到类之类。
也可以说是类指针~


猜你喜欢

转载自blog.csdn.net/qu1993/article/details/77448425