如何使用类引用创建对象的实例,以及
确保构造函数被执行?
确保构造函数被执行?
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类”)。