gpt4 book ai didi

Delphi:使用接口(interface)调用父构造函数(Spring4D框架)

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

我面临着从 Spring4D 框架容器解析的类型正确实例化对象的问题。

我有一个类:

type
TSurvey = class ( TInterfacedObject, ISurvey )

private
_id : Integer;
_organization : IOrganization;

function GetId () : Integer;
procedure SetId ( const value : Integer );

function GetOrganization () : IOrganization;
procedure SetOrganization ( const value : IOrganization);

public
property Id : Integer read GetId write SetId;
property Organization: IOrganization read GetOrganization write SetOrganization;
end;

...

initialization

GlobalContainer.RegisterType<TSurvey>.Implements<ISurvey>.InjectField ( '_organization' );

...

我使用 GlobalContainer 来实例化一个对象:

survey := GlobalContainer.Resolve<ISurvey>;
survey.Organization.Id := 5;

一切都很好并且工作完美。

现在我想为 TSurvey 创建一个后代类:

type
TFieldSurvey = class ( TSurvey )
...
end;

问题是如何正确实例化 TFieldSurvey 类的对象?

如果我使用Create(),那么我会得到一个异常:

 fieldSurvey := TFieldSurvey.Create ();
fieldSurvey.Organization.Id := 5 <- exception is here

我是否必须在 TFieldSurvey 构造函数中显式调用组织字段的构造函数,还是有其他方法?例如,使用GlobalContainer?

提前致谢。

最佳答案

只有当您通过容器创建对象时,注入(inject)才会起作用,而不是直接调用对象的构造函数。因此,您需要向 GlobalContainer 注册 TFieldSurvey,然后调用 Resolve 来获取您的对象。

注册:

GlobalContainer.RegisterType<TSurvey>.Implements<ISurvey>('SPRING_SURVEY').InjectField ( '_organization' );
GlobalContainer.RegisterType<TFieldSurvey>.Implements<ISurvey>('SPRING_FIELD_SURVEY').InjectField ( '_organization' );

然后获取实例:

GlobalContainer.Resolve<ISurvey>('SPRING_FIELD_SURVEY')

我添加了“SPRING_SURVEY”和“SPRING_FIELD_SURVEY”的名称,因为它们都实现了 ISurvey,这可以让您选择所需的类实例,否则您最终会得到为该接口(interface)注册的最后一个实现。如果TFieldSurvey 要实现其自己的接口(interface)(例如IFieldSurvey),您可以删除名称,然后根据需要将其类型转换回ISurvey

您始终可以在 _organization 字段上使用 [Inject] 属性,而不是使用 .InjectField(在将 Global.Container.Common 添加到您的使用中之后):

  TSurvey = class ( TInterfacedObject, ISurvey )
private
_id : Integer;
[Inject]
_organization : IOrganization;

function GetId () : Integer;
procedure SetId ( const value : Integer );

function GetOrganization () : IOrganization;
procedure SetOrganization ( const value : IOrganization);

public
property Id : Integer read GetId write SetId;
property Organization: IOrganization read GetOrganization write SetOrganization;
end;

您的注册将是:

  GlobalContainer.RegisterType<TSurvey>.Implements<ISurvey>('SPRING_SURVEY');
GlobalContainer.RegisterType<TFieldSurvey>.Implements<ISurvey>('SPRING_FIELD_SURVEY');

关于Delphi:使用接口(interface)调用父构造函数(Spring4D框架),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31737967/

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