2009年5月29日

Delphi 以類別名稱來建立有建構參數的物件


type
// ...

TMyParent = class(TComponent)
public
function echo(name: string): string; virtual; abstract;
end;

TMyParentClass = class of TMyParent;

TMySub1 = class(TMyParent)
private
s: string;
public
constructor Create(AOwner: TComponent); override;
function echo(name: string): string; override;
end;

// ...

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
var
PClass: TPersistentClass;
Obj: TMyParent;
begin
RegisterClass(TMySub1);
PClass := FindClass('TMySub1');
Obj := TMyParentClass(PClass).Create(Self);
Caption := Obj.echo('Solnone');
UnRegisterClass(TMySub1);
end;

constructor TMySub1.Create(AOwner: TComponent);
begin
s := AOwner.GetNamePath + ' TMySub1 ';
end;

function TMySub1.echo(name: string): string;
begin
Result := s+ 'Hello ' + name;
end;

// Form1 TMySub1 Hello Solnone

沒有留言:

網誌存檔