A constructor can be called using
a variable of a class-reference type. This allows construction of objects whose
type isn’t known at compile time. For example,
type
TControlClass = class of TControl;
function
CreateControl(ControlClass: TControlClass;
const ControlName: string; X, Y, W, H: Integer): TControl;
begin
Result := ControlClass.Create(MainForm);
with Result do
begin
Parent := MainForm;
Name := ControlName;
SetBounds(X, Y, W, H);
Visible := True;
end;
end;
The CreateControl function
requires a class-reference parameter to tell it what kind of control to create.
It uses this parameter to call the class’s constructor. Because class-type
identifiers denote class-reference values, a call to CreateControl can
specify the identifier of the class to create an instance of. For example,
CreateControl(TEdit, 'Edit1', 10, 10,
100, 20);
Constructors called using class references are usually virtual. The constructor implementation activated by the call depends on the runtime type of the class reference.
构造器可以被类引用类型的变量调用。这就允许在编译时构造类型未知的对象。例如,
type
TControlClass = class of TControl;
function
CreateControl(ControlClass: TControlClass;
const ControlName: string; X, Y, W, H: Integer): TControl;
begin
Result := ControlClass.Create(MainForm);
with Result do
begin
Parent := MainForm;
Name := ControlName;
SetBounds(X, Y, W, H);
Visible := True;
end;
end;
上面的例子中,CreateControl函数需要一个类引用类型告诉它何种控件被创建。该函数用这一参数调用类的构造器。因为类类型标识符表示类引用的值,所以对CreateControl调用可以指定类的标识符以创建相应的对象。例如,
CreateControl(TEdit, 'Edit1', 10, 10,
100, 20);
用类引用调用的构造器通常是虚拟的。运行时类引用的类型决定了构造器在调用时的具体实现。