Delphi中的接口多态性

时间:2013-05-22 07:52:44

标签: delphi oop interface delphi-7

我有两个来自antoher的接口:

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

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

现在我有一个参数是ISomeInterface的过程,如:

procedure DoSomething(SomeInterface: ISomeInterface);

我想检查SomeInterface是否是ISomeInterfaceChild。 Delphi 7中的接口不支持Is运算符,我也不能使用Supports。我该怎么办?

2 个答案:

答案 0 :(得分:5)

您确实可以使用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

答案 1 :(得分:4)

为什么你说你不能使用Supports功能?它似乎是解决方案,它有一个重载版本,它将IInterface作为第一个参数,所以

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

应该做你想做的事。

相关问题