Eduardo Elias
Eduardo Elias

Reputation: 1760

How to find out that a concrete class object is already in a TInterfaceList?

I have an Interface called ISupport that is used to supply tech support information.

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

Each class that has relevant information for support implements this Interface, and at the constructor calls:

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

Example of usage (partial):

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;

Later on the code I can go over the list and call the AddReport just fine.

My problem is that there are one class, this TyConfig, that is instantiated many times, and the information it will report is exactly the same. The FInterfaceList.IndexOf only avoid the very same interface to be added.

I want to avoid that the ISupport from TyConfig gets registered more than one time.

Upvotes: 0

Views: 185

Answers (1)

David Heffernan
David Heffernan

Reputation: 613332

Starting from Delphi 2010 it is possible to cast from an interface to an object:

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

Once you have that capability, it is a small step to check that the object is derived from a particular class:

if obj is TyConfig then
  ....

With these pieces, you should be able to solve your problem.

Upvotes: 2

Related Questions