gpt4 book ai didi

delphi - 使用初始化部分进行模块注册是个好主意吗?

转载 作者:行者123 更新时间:2023-12-03 14:41:00 26 4
gpt4 key购买 nike

我正在寻找一个好的去中心化模块注册解决方案。

我不希望单个单元使用项目的所有模块单元,但我宁愿让模块单元自行注册。

我能想到的唯一解决方案是依赖 Delphi 单元的初始化

我写了一个测试项目:

单元2

TForm2 = class(TForm)
private
class var FModules: TDictionary<string, TFormClass>;
public
class property Modules: TDictionary<string, TFormClass> read FModules;
procedure Run(const AName: string);
end;

procedure TForm2.Run(const AName: string);
begin
FModules[AName].Create(Self).ShowModal;
end;

initialization
TForm2.FModules := TDictionary<string, TFormClass>.Create;

finalization
TForm2.FModules.Free;

单元3

TForm3 = class(TForm)

implementation

uses
Unit2;

initialization
TForm2.Modules.Add('Form3', TForm3);

单元4

TForm4 = class(TForm)

implementation

uses
Unit2;

initialization
TForm2.Modules.Add('Form4', TForm4);

但这有一个缺点。是否保证我的注册单元(在本例中为 Unit2s)initialization 部分始终首先运行?

我经常阅读有关初始化部分的警告,我知道我必须避免在其中引发异常。

最佳答案

Is it a good idea to use initialization sections for module registration?

是的。 Delphi自己的框架也使用它,例如TGraphic-后代的注册。

Is it guaranteed that my registration units (in this case Unit2s) initialization section is always run first?

是的,根据 docs :

For units in the interface uses list, the initialization sections of the units used by a client are executed in the order in which the units appear in the client's uses clause.

但请注意您使用 runtime packages 的情况.

关于delphi - 使用初始化部分进行模块注册是个好主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22733038/

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