Delphi中的接口多态性

Delphi中的接口多态性,delphi,oop,interface,delphi-7,Delphi,Oop,Interface,Delphi 7,我有两个接口,一个来自antoher: type ISomeInterface = interface ['{5A46CC3C-353A-495A-BA89-48646C4E5A75}'] end; ISomeInterfaceChild = interface(ISomeInterface) ['{F64B7E32-B182-4C70-A5B5-72BAA92AAADE}'] end; 现在我有一个过程,参数如下: procedure DoSomething

我有两个接口,一个来自antoher:

type
  ISomeInterface = interface
    ['{5A46CC3C-353A-495A-BA89-48646C4E5A75}']
  end;

  ISomeInterfaceChild = interface(ISomeInterface)
    ['{F64B7E32-B182-4C70-A5B5-72BAA92AAADE}']
  end;
现在我有一个过程,参数如下:

procedure DoSomething(SomeInterface: ISomeInterface);

我想检查某个接口是否为ISomeInterfaceChild<在Delphi 7的界面中不支持代码>Is运算符,我也不能在这里使用
Supports
。我能做什么?

您确实可以使用
支持。您所需要的只是:

Supports(SomeInterface, ISomeInterfaceChild)
该程序说明:

program SupportsDemo;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  ISomeInterface = interface
    ['{5A46CC3C-353A-495A-BA89-48646C4E5A75}']
  end;

  ISomeInterfaceChild = interface(ISomeInterface)
    ['{F64B7E32-B182-4C70-A5B5-72BAA92AAADE}']
  end;

procedure Test(Intf: ISomeInterface);
begin
  Writeln(BoolToStr(Supports(Intf, ISomeInterfaceChild), True));
end;

type
  TSomeInterfaceImpl = class(TInterfacedObject, ISomeInterface);
  TSomeInterfaceChildImpl = class(TInterfacedObject, ISomeInterface, ISomeInterfaceChild);

begin
  Test(TSomeInterfaceImpl.Create);
  Test(TSomeInterfaceChildImpl.Create);
  Readln;
end.
输出

False True 假的 真的
你为什么说你不能使用这个功能?这似乎是解决方案,它有一个重载版本,它将
IInterface
作为第一个参数

procedure DoSomething(SomeInterface: ISomeInterface);
var tmp: ISomeInterfaceChild;
begin
  if(Supports(SomeInterface, ISomeInterfaceChild, tmp))then begin
     // argument is ISomeInterfaceChild
  end;

应该做你想做的。

如果只需要检查接口是否支持
ISomeInterfaceChild
那么你使用了错误的重载。正如我在回答中所演示的,您应该使用两个参数重载。好吧,我假设如果您需要检查的是参数
ISomeInterfaceChild
,您还需要将其作为
ISomeInterfaceChild
使用。否则,检查不太有意义,它应该无关紧要,因此检查它可能表明存在设计问题。@ain:不一定。有时,接口用于公布包含对象的特性,而不实际为其公开新函数。在这种情况下,只需检查支持的接口是否存在就足够了。