我有这些接口声明:
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;
答案 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;