gpt4 book ai didi

string - Delphi - 从字符串表单名称创建自定义表单实例(使用自定义构造函数创建)

转载 作者:行者123 更新时间:2023-12-01 19:32:37 27 4
gpt4 key购买 nike

我目前对使用字符串表单名称创建表单(如 Is there a way to instantiate a class by its name in delphi? )感到困惑,但我的表单有自己的构造函数创建。

//-BASE CLASS-//
TBaseForm = class(TForm)
constructor Create(param1, param2: string); overload;
protected
var1, var2: string;
end;

constructor TBaseForm.Create(param1, param2: string);
begin
inherited Create(Application);
var1 := param1;
var2 := param2;
end;

//-REAL CLASS-//
TMyForm = class(TBaseForm)
end;

//-CALLER-//
TCaller = class(TForm)
procedure Btn1Click(Sender: TObject);
procedure Btn2Click(Sender: TObject);
end;

uses UnitBaseForm, UnitMyForm;

procedure TCaller.Btn1Click(Sender: TObject);
begin
TMyForm.Create('x', 'y');
end;

procedure TCaller.Btn1Click(Sender: TObject);
var PC: TPersistentClass;
Form: TForm;
FormBase: TBaseForm;
begin
PC := GetClass('TMyForm');

// This is OK, but I can't pass param1 & 2
Form := TFormClass(PC).Create(Application);

// This will not error while compiled, but it will generate access violation because I need to create MyForm not BaseForm.
FormBase := TBaseForm(PC).Create('a', 'z');
end;

根据我提供的代码,如何仅通过字符串表单名称来创建动态自定义构造函数表单?还是真的不可能? (我开始认为这是不可能的)

最佳答案

您需要定义 TBaseForm 数据类型的,然后将结果强制转换为 GetClass() 为该类型,然后您可以调用构造函数。您还需要将构造函数声明为 virtual,以便可以正确调用派生类构造函数。

试试这个:

type
TBaseForm = class(TForm)
public
constructor Create(param1, param2: string); virtual; overload;
protected
var1, var2: string;
end;

TBaseFormClass = class of TBaseForm;

.

procedure TCaller.Btn1Click(Sender: TObject);
var
BF: TBaseFormClass;
Form: TBaseForm;
begin
BF := TBaseFormClass(GetClass('TMyForm'));
Form := BF.Create('a', 'z');
end;

关于string - Delphi - 从字符串表单名称创建自定义表单实例(使用自定义构造函数创建),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13064719/

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