How can I create an Delphi object from a class reference and ensure constructor execution?

前端 未结 5 756
别那么骄傲
别那么骄傲 2020-12-01 04:26

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

In this code example, the constructor of TMyClass wi

5条回答
  •  被撕碎了的回忆
    2020-12-01 05:05

    Your code slightly modified:

    type
      TMyObject = class(TObject)
        MyStrings: TStrings;
        constructor Create; virtual;
      end;
      TMyClass = class of TMyObject;
    
    constructor TMyObject.Create;
    begin
      inherited Create;
      MyStrings := TStringList.Create;
    end;
    
    procedure Test; 
    var
      C: TMyClass;
      Instance: TObject;
    begin
       C := TMyObject;
       Instance := C.Create;
    end;
    

提交回复
热议问题