相关疑难解决方法(0)

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

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

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

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;
Run Code Online (Sandbox Code Playgroud)

delphi constructor reference class delphi-2009

20
推荐指数
4
解决办法
4万
查看次数

使用类引用的多态性和继承(第2部分)?

下面的控制台应用程序给出了"运行时错误"......

为什么会这样?非常感谢 !

PS:相关SO帖子

program Project2;

{$APPTYPE CONSOLE}

type
  TParent = class;
  TParentClass = class of TParent;

  TParent = class
  public
    procedure Work; virtual; abstract;
  end;

  TChild1 = class(TParent)
  public
    procedure Work; override;
  end;

  TChild2 = class(TParent)
  public
    procedure Work; override;
  end;

procedure TChild1.Work;
begin
  WriteLn('Child1 Work');
end;

procedure TChild2.Work;
begin
  WriteLn('Child2 Work');
end;

procedure Test(ImplClass: TParentClass);
var
  ImplInstance: TParent;
begin
  ImplInstance := ImplClass.Create;
  ImplInstance.Work;
  ImplInstance.Free;
end;

begin
  Test(TParent);
  Test(TChild1);
  Test(TChild2);
  Readln;
end.
Run Code Online (Sandbox Code Playgroud)

delphi polymorphism inheritance reference class

1
推荐指数
1
解决办法
172
查看次数