gpt4 book ai didi

delphi - 创建 Delphi IoC。如何禁用 Delphi 的链接器删除未使用的类

转载 作者:行者123 更新时间:2023-12-03 15:01:13 24 4
gpt4 key购买 nike

我在 delphi 中创建了一个 IoC,能够自动注册任何具有 IocSingletonAttribute 的类。

自动注册如下所示。

procedure TIocContainer.AutoRegister;
var
ctx: TRttiContext;
rType: TRttiType;
attr: TCustomAttribute;
&Type: PTypeInfo;
begin
ctx := TRttiContext.Create;
for rType in ctx.GetTypes do
Begin
for attr in rType.GetAttributes do
Begin
if TypeInfo(IocSingletonAttribute) = attr.ClassInfo then
Begin
&Type := IocSingletonAttribute(attr).&Type;
RegisterType(&Type, rType.Handle, True);
End;
End;
End;
end;

然后,我创建一个实现并向其中添加 IocSingletonAttribute。看起来像这样

[IocSingleton(TypeInfo(IIocSingleton))]
TIocSingleton = class(TInterfacedObject, IIocSingleton)
procedure DoSomeWork;
end;

现在我们来看看程序的实际代码。如果我在下面编写代码,IoC 将不起作用。 AutoRegister 过程没有获取 TIocSingleton。

var
Ioc: TIocContainer;
Singleton: IIocSingleton;
begin
Ioc := TIocContainer.Create;
try
Ioc.AutoRegister;
Singleton := Ioc.Resolve<IIocSingleton>();
Singleton.DoSomeWork;
finally
Ioc.Free;
end;
end.

但是如果我编写下面的代码,一切都会按预期工作。请注意我如何声明 TIocSingleton 类并使用它。

var
Ioc: TIocContainer;
Singleton: IIocSingleton;
ASingleton: TIocSingleton;
begin
Ioc := TIocContainer.Create;
ASingleton := TIocSingleton.Create;
try
Ioc.AutoRegister;
Singleton := Ioc.Resolve<IIocSingleton>();
Singleton.DoSomeWork;
finally
Singleton.Free;
Ioc.Free;
end;
end.
因此,基于此,我假设 Delphi 的编译器链接器正在第一个示例中删除 TIocSingleton,因为它从未在应用程序的任何部分中显式使用。所以我的问题是,是否可以为某个类关闭编译器的“删除未使用的代码”功能?或者,如果我的问题不是链接器,任何人都可以解释为什么第二个示例有效但第一个示例无效?

最佳答案

{$STRONGLINKTYPES ON} 指令添加到 .dpr。那么这些类型应该包括在内。但它肯定会毁掉你的应用程序,因为它不适用于单个类。

关于delphi - 创建 Delphi IoC。如何禁用 Delphi 的链接器删除未使用的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42054460/

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