如何检查接口对象是否实现另一个接口?

时间:2013-01-15 16:30:35

标签: delphi oop interface

我有这些接口声明:

IListener = interface
  procedure HandleEvent(AEvent: TMyEvent);
end;

IExtendedListener = interface(IListener)
  ['{85A3456A-D5E5-4F37-ABDD-A75A7B3B494C}']  // required by GetInterface
  procedure HandleExtendedEvent(AExtendedEvent: TMyExtendedEvent);
end;

给定实现IListener的东西的接口引用,如何检查它是否也实现了IExtendedListener?我正在使用代码下面的代码,因为执行像if Listener is IExtendedListener then ...这样的编译时错误。

TSomeClass.Notify(AEvent: TMyExtendedEvent);
var
  Listener: IListener;
  ExtListener: IExtendedListener;
  Obj: TObject;
begin
  for Listener in FListeners do
  begin
    // works but smells funny
    Obj := Listener as TObject;
    Obj.GetInterface(IExtendedListener, ExtListener);
    if Assigned(ExtListener) then
      ExtNotifyee.HandleExtendedEvent(AEvent);
  end;
end;

1 个答案:

答案 0 :(得分:19)

您应该使用Sysutils.Supports来检查特殊界面

uses
  SysUtils;

TSomeClass.Notify(AEvent: TMyExtendedEvent);
var
  Listener    : IListener;
  ExtListener : IExtendedListener;
begin
  for Listener in FListeners do
    if Supports( Listener, IExtendedListener, ExtListener ) then
      ExtListener.HandleExtendedEvent( AEvent );
end;