最近我發現了一段從字符串創建TButton實例的代碼:'TButton'被用作參數。如何從提供類名稱的字符串創建實例?
見"Is there a way to instantiate a class by its name in Delphi?"
我想任何對象的published屬性保存到一個XML文件(正常工作),最近我想重新從XML文件中的這些對象。在這個文件中寫入了應該創建哪個類(例如TButton),然後跟隨一個屬性列表,該列表應該加載到此運行時創建的對象中。
上面的例子顯示瞭如何做到這一點,但它不適用於我自己的類。見下面的代碼:
TTripple=class (TPersistent)
FFont:TFont;
public
constructor Create;
Destructor Destroy;override;
published
property Font:TFont read FFont write FFont;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
constructor TTripple.Create;
begin
inherited;
FFont:=TFont.Create;
end;
destructor TTripple.Destroy;
begin
FFont.Free;
inherited;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
RegisterClasses([TButton, TForm, TTripple]);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
CRef : TPersistentClass;
APer : TPersistent;
begin
// CRef := GetClass('TButton');
CRef := GetClass('TTripple');
if CRef<>nil then
begin
APer := TPersistent(TPersistentClass(CRef).Create);
ShowMessage(APer.ClassName); // shows TTripple, what is correct
if APer is TTripple then (APer as TTripple).Font.Color:=90;
/// Here I get error message, because TTriple was not created... ?!?!?!
end;
end;
我不能通過。 TTripple對象可能已創建,但其構造函數未使用。
非常感謝,梅森。它現在的作品....非凡... :-) – lyborko 2009-12-08 14:13:37
很高興能夠幫助! – 2009-12-08 14:27:15