gpt4 book ai didi

delphi - 如何从提供类名的字符串创建实例?

转载 作者:行者123 更新时间:2023-12-03 15:20:40 25 4
gpt4 key购买 nike

最近我发现了一段从字符串创建 TButton 实例的代码:'TButton' 被用作参数。

参见"Is there a way to instantiate a class by its name in Delphi?"

我正在尝试将任何对象的已发布属性保存到 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 对象可能已创建,但未使用其构造函数。

最佳答案

TRipple 构造函数没有被调用,因为它不是虚拟的。

当您从类引用构造对象时,编译器还不知道最终的类类型是什么,因此它无法在代码中分配正确的构造函数。它所知道的只是它是从 TPeristent 派生的,因此它编写代码来调用 TPersistent 的构造函数,即 TObject.Create。如果您想调用正确的构造函数,则必须以虚拟方式进行。

已经定义了一个虚拟构造函数,用于从类名中读取类。它在 TComponent 中定义。让 TRipple 继承自 TComponent 并重写其虚拟构造函数(将 Owner 作为参数的构造函数),然后您的代码就可以工作。

关于delphi - 如何从提供类名的字符串创建实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1866180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com