如何从类引用创建 Delphi 对象并确保构造函数执行? [英] How can I create an Delphi object from a class reference and ensure constructor execution?

查看:21
本文介绍了如何从类引用创建 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").

这篇关于如何从类引用创建 Delphi 对象并确保构造函数执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆