http://www.wretch.cc/blog/solnone/14198678
若想用父類別來操作,而不想 use 各子類別,則可以類別名稱來動態建立子類別物件
在 unit Classes 中,有RegisterClass, GetClass, FindClass 和 UnRegisterClass
先使用 RegisterClass 註冊所需動態建立的類別
然後才能使用 GetClass 或 FindClass 以類別名稱來找出註冊過的類別
再轉型為所需的父類別來建立並使用物件
若不再需要它,則可以使用 UnRegisterClass 來取消註冊
procedure TForm1.FormCreate(Sender: TObject);
var
PClass: TPersistentClass;
Strings: TStrings;
begin
PClass := FindClass('TStringList');
Strings := PClass.Create as TStrings;
try
Strings.Add('Hi');
finally
Strings.Free;
end;
end;
initialization
RegisterClass(TStringList);
finalization
UnRegisterClass(TStringList);
﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍﹍
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
end;
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;
var
Form1: TForm1;
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;
{ TMySub1 }
constructor TMySub1.Create(AOwner: TComponent);
begin
s := AOwner.GetNamePath + ' TMySub1 ';
end;
function TMySub1.echo(name: string): string;
begin
Result := s+ 'Hello ' + name;
end;
end.
轉貼至 http://chuanitai.pixnet.net/blog/post/37036289-delphi-%E4%BB%A5%E9%A1%9E%E5%88%A5%E5%90%8D%E7%A8%B1%E4%BE%86%E5%BB%BA%E7%AB%8B%E7%89%A9%E4%BB%B6
沒有留言:
張貼留言