如何从类引用创建一个Delphi对象并确保构造函数执行?

问题描述:

如何使用类引用创建对象的实例,
确保构造函数被执行?

How can I create an instance of an object using a class reference, and ensure that the constructor is executed?

在此代码示例中,不会调用TMyClass的构造函数:

In this code example, the constructor of TMyClass will not be called:

type
   TMyClass = class(TObject)
     MyStrings: TStrings;
     constructor Create; virtual;
   end;

constructor TMyClass.Create;
begin
   MyStrings := TStringList.Create;
end;

procedure Test;
var
   Clazz: TClass;
   Instance: TObject;
begin
   Clazz := TMyClass;
   Instance := Clazz.Create;
end;


使用:

type
  TMyClass = class(TObject)
    MyStrings: TStrings;
    constructor Create; virtual;
  end;
  TMyClassClass = class of TMyClass; // <- add this definition

constructor TMyClass.Create;
begin
   MyStrings := TStringList.Create;
end;

procedure Test;
var
  Clazz: TMyClassClass; // <- change TClass to TMyClassClass
  Instance: TObject;
begin
   Clazz := TMyClass; // <- you can use TMyClass or any of its child classes. 
   Instance := Clazz.Create; // <- virtual constructor will be used
end;

或者,可以使用类型转换到TMyClass(而不是TMyClass类)。

Alternatively, you can use a type-casts to TMyClass (instead of "class of TMyClass").