0

我有一个名为 ISupport 的接口,用于提供技术支持信息。

ISupport = Interface(IInterface)
  procedure AddReport(const Report: TStrings);
End;

每个具有相关支持信息的类都实现了这个接口,并在构造函数处调用:

procedure TySupport.RegisterSupport(Support: ISupport);
begin
  if FInterfaceList.IndexOf(Support) = -1 then
    FInterfaceList.Add(Support);
end;

使用示例(部分):

TyConfig = class(TInterfacedObject, ISupport)
private
  procedure   AddReport(const Report: TStrings);

public
  constructor Create;
end;

constructor TyConfig.Create;
begin
  if Assigned(ySupport) then
    ySupport.RegisterSupport(Self);
end;

稍后在代码中,我可以查看列表并调用 AddReport 就好了。

我的问题是有一个类,这个TyConfig,它被实例化了很多次,它会报告的信息是完全一样的。FInterfaceList.IndexOf 只避免添加相同的接口。

我想避免来自 TyConfig 的 ISupport 被多次注册。

4

1 回答 1

2

从 Delphi 2010 开始,可以从接口转换为对象:

var
  obj: TObject;
  intf: IInterface;
....
obj := intf as IInterface;

一旦你拥有了这种能力,只需一小步就可以检查对象是否派生自特定类:

if obj is TyConfig then
  ....

有了这些作品,您应该能够解决您的问题。

于 2013-08-30T18:45:21.783 回答